基于Spring怎么整合mybatis的mapper

发布时间:2023-03-11 14:23:54 作者:iii
来源:亿速云 阅读:148

基于Spring怎么整合MyBatis的Mapper

1. 引言

在现代Java企业级应用开发中,Spring框架和MyBatis是两个非常流行的技术栈。Spring提供了强大的依赖注入和面向切面编程的能力,而MyBatis则是一个优秀的持久层框架,能够简化数据库操作。将两者结合起来,可以充分发挥各自的优势,提高开发效率和代码质量。

本文将详细介绍如何在Spring框架中整合MyBatis的Mapper,包括环境搭建、配置文件的编写、Mapper接口的定义、以及如何在Spring中使用这些Mapper接口。通过本文的学习,读者将能够掌握Spring与MyBatis整合的核心技术,并能够在实际项目中应用这些知识。

2. 环境准备

在开始整合之前,我们需要准备好开发环境。以下是所需的主要工具和依赖:

2.1 创建Maven项目

首先,我们创建一个Maven项目。可以使用IDE(如IntelliJ IDEA或Eclipse)创建,也可以使用命令行工具。

mvn archetype:generate -DgroupId=com.example -DartifactId=spring-mybatis-demo -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

2.2 添加依赖

pom.xml中添加Spring、MyBatis和MySQL的依赖:

<dependencies>
    <!-- Spring Core -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.3.21</version>
    </dependency>

    <!-- Spring JDBC -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.3.21</version>
    </dependency>

    <!-- MyBatis -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.9</version>
    </dependency>

    <!-- MyBatis-Spring -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>2.0.7</version>
    </dependency>

    <!-- MySQL Connector -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.29</version>
    </dependency>

    <!-- 其他依赖 -->
    <dependency>
        <groupId>javax.annotation</groupId>
        <artifactId>javax.annotation-api</artifactId>
        <version>1.3.2</version>
    </dependency>
</dependencies>

2.3 配置数据库

src/main/resources目录下创建application.properties文件,配置数据库连接信息:

spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_demo?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=yourpassword
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

3. Spring配置

3.1 配置数据源

在Spring中,我们需要配置一个数据源(DataSource),以便MyBatis能够连接到数据库。可以使用Spring的DataSource实现,如DriverManagerDataSourceHikariDataSource

@Configuration
public class DataSourceConfig {

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/mybatis_demo?useSSL=false&serverTimezone=UTC");
        dataSource.setUsername("root");
        dataSource.setPassword("yourpassword");
        return dataSource;
    }
}

3.2 配置SqlSessionFactory

SqlSessionFactory是MyBatis的核心接口,用于创建SqlSession。我们需要在Spring中配置一个SqlSessionFactoryBean,它将负责创建SqlSessionFactory

@Configuration
public class MyBatisConfig {

    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mappers/*.xml"));
        return sessionFactory.getObject();
    }
}

3.3 配置MapperScannerConfigurer

为了自动扫描Mapper接口并将其注册为Spring的Bean,我们需要配置MapperScannerConfigurer

@Configuration
public class MyBatisConfig {

    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer scannerConfigurer = new MapperScannerConfigurer();
        scannerConfigurer.setBasePackage("com.example.mapper");
        return scannerConfigurer;
    }
}

4. 定义Mapper接口

4.1 创建实体类

首先,我们创建一个简单的实体类User,用于映射数据库中的用户表。

public class User {
    private Long id;
    private String username;
    private String email;

    // Getters and Setters
}

4.2 创建Mapper接口

接下来,我们定义一个Mapper接口UserMapper,用于操作User表。

public interface UserMapper {
    User selectUserById(Long id);
    List<User> selectAllUsers();
    void insertUser(User user);
    void updateUser(User user);
    void deleteUser(Long id);
}

4.3 编写Mapper XML文件

src/main/resources/mappers目录下创建UserMapper.xml文件,定义SQL语句。

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.example.mapper.UserMapper">

    <select id="selectUserById" resultType="com.example.model.User">
        SELECT * FROM users WHERE id = #{id}
    </select>

    <select id="selectAllUsers" resultType="com.example.model.User">
        SELECT * FROM users
    </select>

    <insert id="insertUser" parameterType="com.example.model.User">
        INSERT INTO users (username, email) VALUES (#{username}, #{email})
    </insert>

    <update id="updateUser" parameterType="com.example.model.User">
        UPDATE users SET username = #{username}, email = #{email} WHERE id = #{id}
    </update>

    <delete id="deleteUser" parameterType="Long">
        DELETE FROM users WHERE id = #{id}
    </delete>

</mapper>

5. 使用Mapper接口

5.1 创建Service层

在Service层中,我们可以通过注入Mapper接口来使用它。

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    public User getUserById(Long id) {
        return userMapper.selectUserById(id);
    }

    public List<User> getAllUsers() {
        return userMapper.selectAllUsers();
    }

    public void addUser(User user) {
        userMapper.insertUser(user);
    }

    public void updateUser(User user) {
        userMapper.updateUser(user);
    }

    public void deleteUser(Long id) {
        userMapper.deleteUser(id);
    }
}

5.2 创建Controller层

在Controller层中,我们可以调用Service层的方法来处理HTTP请求。

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/{id}")
    public User getUser(@PathVariable Long id) {
        return userService.getUserById(id);
    }

    @GetMapping
    public List<User> getAllUsers() {
        return userService.getAllUsers();
    }

    @PostMapping
    public void addUser(@RequestBody User user) {
        userService.addUser(user);
    }

    @PutMapping
    public void updateUser(@RequestBody User user) {
        userService.updateUser(user);
    }

    @DeleteMapping("/{id}")
    public void deleteUser(@PathVariable Long id) {
        userService.deleteUser(id);
    }
}

6. 测试

6.1 启动Spring Boot应用

确保所有配置和代码都正确无误后,启动Spring Boot应用。

mvn spring-boot:run

6.2 使用Postman测试API

使用Postman或其他HTTP客户端工具,测试我们定义的API接口。

7. 总结

通过本文的学习,我们详细介绍了如何在Spring框架中整合MyBatis的Mapper。从环境准备、Spring配置、Mapper接口的定义,到在Service和Controller层中使用Mapper接口,我们一步步完成了整个整合过程。

Spring与MyBatis的整合不仅简化了数据库操作,还提高了代码的可维护性和可扩展性。希望本文能够帮助读者在实际项目中更好地应用Spring和MyBatis,提升开发效率和代码质量。

8. 参考资料


注意:本文中的代码示例仅供参考,实际项目中可能需要根据具体需求进行调整。

推荐阅读:
  1. 详解Spring-bean的循环依赖以及解决方式
  2. springboot在服务器上的几种启动方式(小结)

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

spring mybatis mapper

上一篇:Git怎么使用reset或revert方法恢复之前的版本

下一篇:如何通过Java连接SQL Server数据库

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》