MyBatis 与 Spring 的集成提高了开发效率,简化了配置,并使事务管理变得轻松。下面是将 MyBatis 集成到 Spring 应用程序中的一般步骤,包括配置和代码示例。
1. 添加依赖
首先,确保在项目的pom.xml
中添加了 MyBatis、MyBatis-Spring 适配器和 Spring 相关的 Maven 依赖。如果您使用的是 Spring Boot,则可以添加mybatis-spring-boot-starter
依赖,这个 Starter 会自动配置大部分需要的设置。
<!-- Spring Boot 的父项目 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.x.x.RELEASE</version>
</parent>
<!-- MyBatis Spring Boot Starter -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.x.x</version>
</dependency>
2. 配置数据源
在 Spring 的配置文件中(比如application.properties
或者application.yml
,如果是传统的 Spring 项目,则可能是 XML 配置文件),配置数据库连接和 MyBatis 相关的属性。
# 数据源配置
spring.datasource.url=jdbc:mysql://localhost:3306/your_database?useSSL=false&serverTimezone=UTC
spring.datasource.username=db_user
spring.datasource.password=db_password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# MyBatis Mapper 文件位置
mybatis.mapper-locations=classpath:mapper/*.xml
# 实体类别名包
mybatis.type-aliases-package=com.yourpackage.model
3. 配置 MyBatis Mapper 接口
在你的项目中创建 MyBatis 的 Mapper 接口。Spring 将自动扫描这些接口并创建它们的实现。
package com.yourpackage.mapper;
import com.yourpackage.model.YourModel;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface YourModelMapper {
YourModel selectByPrimaryKey(Integer id);
}
4. 编写 Mapper XML 文件
在指定的路径下(如上述配置的mybatis.mapper-locations
所示),创建 MyBatis 的 XML Mapper 文件来定义 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.yourpackage.mapper.YourModelMapper">
<select id="selectByPrimaryKey" resultType="com.yourpackage.model.YourModel">
SELECT id, name
FROM your_table
WHERE id = #{id}
</select>
</mapper>
5. 服务层和控制器
在服务层中注入 Mapper 接口,并使用它来访问数据库。然后,你可以在控制器中调用服务层的方法。
@Service
public class YourModelService {
@Autowired
private YourModelMapper yourModelMapper;
public YourModel getYourModelById(Integer id) {
return yourModelMapper.selectByPrimaryKey(id);
}
}
@RestController
@RequestMapping("/yourmodel")
public class YourModelController {
@Autowired
private YourModelService yourModelService;
@GetMapping("/{id}")
public YourModel getYourModelById(@PathVariable Integer id) {
return yourModelService.getYourModelById(id);
}
}
这样,你就完成了 MyBatis 与 Spring 的集成。如果你使用的是 Spring Boot,许多配置会自动完成,你只需要关注业务逻辑的实现。这种集成方式提供了强大的数据访问能力,同时保持了代码的简洁性和可维护性。