您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# Spring Boot 2.x整合Mybatis的方式有哪些
## 前言
MyBatis作为一款优秀的持久层框架,在Spring Boot生态中有着广泛的应用。Spring Boot 2.x版本提供了多种与MyBatis整合的方式,开发者可以根据项目需求选择最适合的整合方案。本文将详细介绍三种主流整合方式及其实现细节。
## 一、官方starter整合(推荐方式)
### 1. 引入依赖
```xml
<!-- Spring Boot MyBatis官方starter -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<!-- 数据库驱动(以MySQL为例) -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
# application.yml
spring:
datasource:
url: jdbc:mysql://localhost:3306/test_db
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
mapper-locations: classpath:mapper/*.xml # XML映射文件位置
type-aliases-package: com.example.model # 实体类包路径
@Mapper // 关键注解
public interface UserMapper {
@Select("SELECT * FROM users WHERE id = #{id}")
User findById(Long id);
}
注解 | 作用 |
---|---|
@Mapper |
标识MyBatis接口 |
@Select |
定义查询SQL |
@Insert |
定义插入SQL |
@Update |
定义更新SQL |
@Delete |
定义删除SQL |
@Results |
结果集映射 |
@Result |
单字段映射 |
@Mapper
public interface ProductMapper {
@Insert("INSERT INTO products(name,price) VALUES(#{name},#{price})")
@Options(useGeneratedKeys = true, keyProperty = "id")
int insert(Product product);
@Select("SELECT * FROM products WHERE id = #{id}")
@Results({
@Result(property = "id", column = "id"),
@Result(property = "name", column = "name"),
@Result(property = "price", column = "price")
})
Product selectById(Long id);
}
src/main/resources
├── application.yml
└── mapper
├── UserMapper.xml
└── ProductMapper.xml
<!-- UserMapper.xml -->
<mapper namespace="com.example.mapper.UserMapper">
<resultMap id="BaseResultMap" type="User">
<id column="id" property="id" />
<result column="username" property="username" />
</resultMap>
<select id="selectAll" resultMap="BaseResultMap">
SELECT * FROM users
</select>
</mapper>
public interface UserMapper {
List<User> selectAll(); // 方法名与XML中的id对应
}
mybatis:
config-location: classpath:mybatis-config.xml # 全局配置文件(可选)
mapper-locations: classpath:mapper/**/*.xml # 支持通配符
@Mapper
public interface OrderMapper {
// 注解方式
@Select("SELECT * FROM orders WHERE id = #{id}")
Order findSimpleOrder(Long id);
// XML方式
Order findComplexOrderWithDetails(Long id);
}
<!-- OrderMapper.xml -->
<select id="findComplexOrderWithDetails" resultMap="OrderDetailResult">
<!-- 复杂关联查询 -->
</select>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.4.1</version>
</dependency>
@Configuration
@MapperScan(basePackages = "com.example.db1", sqlSessionTemplateRef = "db1SqlSessionTemplate")
public class Db1Config {
// 配置第一个数据源...
}
@Configuration
@MapperScan(basePackages = "com.example.db2", sqlSessionTemplateRef = "db2SqlSessionTemplate")
public class Db2Config {
// 配置第二个数据源...
}
整合方式 | 优点 | 缺点 | 适用场景 |
---|---|---|---|
官方starter | 开箱即用,配置简单 | 定制化能力较弱 | 标准项目快速开发 |
纯注解方式 | 无XML,代码直观 | 复杂SQL可读性差 | 简单CRUD操作 |
XML配置方式 | 复杂SQL易维护,支持动态SQL | 需要维护额外文件 | 复杂查询场景 |
混合模式 | 灵活平衡开发效率与维护性 | 风格需要统一 | 中大型项目 |
最终建议:对于新项目推荐使用官方starter+注解为主、XML为辅的混合模式,既能保证开发效率,又能应对复杂查询需求。 “`
注:本文示例代码基于Spring Boot 2.5.x + MyBatis 3.5.x版本,实际使用时请根据具体版本调整依赖和配置。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。