第14章 Spring Boot集成
掌握 MyBatis 在 Spring Boot 中的自动配置和使用
学习进度:56% 代码演示按钮 💻 查看完整代码 - 在线IDE体验
🎯 学习目标
📚
理解核心概念
掌握Spring Boot与MyBatis集成的核心概念和基本原理
🔧
掌握实践技能
学会自动配置、注解开发和REST API设计等实践技巧
💡
了解应用场景
明确在现代化项目中的应用场景和最佳实践
1. Spring Boot集成概述
1.1 集成优势
🚀 自动配置
Spring Boot提供MyBatis自动配置,减少手动配置工作
📦 起步依赖
通过starter依赖快速集成MyBatis相关组件
⚙️ 外部化配置
使用application.yml统一管理配置信息
🔧 开箱即用
最小化配置即可快速启动应用
1.2 核心特性
- 自动配置:自动配置SqlSessionFactory、DataSource等
- 起步依赖:mybatis-spring-boot-starter简化依赖管理
- 配置属性:通过application.yml配置MyBatis属性
- 监控管理:集成Actuator提供应用监控
2. Maven依赖配置
2.1 核心依赖
<dependencies>
<!-- Spring Boot Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- MyBatis Spring Boot Starter -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.3.1</version>
</dependency>
<!-- 数据库驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- Druid连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.18</version>
</dependency>
</dependencies>
2.2 可选依赖
<!-- 分页插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.4.6</version>
</dependency>
<!-- 监控管理 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
3. 应用配置
3.1 启动类配置
@SpringBootApplication
@MapperScan("com.mybatis.springboot.mapper")
@EnableTransactionManagement
public class SpringBootMybatisApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootMybatisApplication.class, args);
}
}
3.2 application.yml配置
# 服务器配置
server:
port: 8080
servlet:
context-path: /mybatis-demo
# Spring配置
spring:
# 数据源配置
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/mybatis_springboot
username: root
password: 123456
# Druid连接池配置
type: com.alibaba.druid.pool.DruidDataSource
druid:
initial-size: 5
min-idle: 5
max-active: 20
max-wait: 60000
# MyBatis配置
mybatis:
config-location: classpath:mybatis-config.xml
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.mybatis.springboot.entity
configuration:
map-underscore-to-camel-case: true
cache-enabled: true
lazy-loading-enabled: true
4. 注解开发
4.1 Mapper接口
@Mapper
public interface UserMapper {
@Select("SELECT * FROM users WHERE id = #{id}")
User selectUserById(Long id);
@Insert("INSERT INTO users (username, email, age) VALUES (#{username}, #{email}, #{age})")
@Options(useGeneratedKeys = true, keyProperty = "id")
int insertUser(User user);
@Update("UPDATE users SET username = #{username}, email = #{email} WHERE id = #{id}")
int updateUser(User user);
@Delete("DELETE FROM users WHERE id = #{id}")
int deleteUser(Long id);
// 分页查询
@Select("SELECT * FROM users LIMIT #{offset}, #{limit}")
List<User> selectUsersByPage(@Param("offset") int offset, @Param("limit") int limit);
}
4.2 动态SQL注解
@Select({
"<script>",
"SELECT COUNT(*) FROM users",
"<where>",
"<if test='username != null and username != \"\"'>",
"AND username LIKE CONCAT('%', #{username}, '%')",
"</if>",
"<if test='email != null and email != \"\"'>",
"AND email LIKE CONCAT('%', #{email}, '%')",
"</if>",
"</where>",
"</script>"
})
int countUsersByCondition(@Param("username") String username, @Param("email") String email);
5. 服务层开发
5.1 服务接口
public interface UserService {
Long createUser(User user);
User getUserById(Long id);
List<User> getAllUsers();
void updateUser(User user);
void deleteUser(Long id);
List<User> getUsersByPage(int page, int size);
Long createUserWithTransaction(String username, String email, Integer age, boolean shouldFail) throws Exception;
}
5.2 服务实现
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public Long createUser(User user) {
userMapper.insertUser(user);
return user.getId();
}
@Override
@Transactional(rollbackFor = Exception.class)
public Long createUserWithTransaction(String username, String email, Integer age, boolean shouldFail) throws Exception {
User user = new User(username, email, age);
userMapper.insertUser(user);
if (shouldFail) {
throw new Exception("模拟业务异常,触发事务回滚");
}
return user.getId();
}
}
6. REST API开发
6.1 控制器实现
@RestController
@RequestMapping("/api/users")
public class UserController {
@Autowired
private UserService userService;
@PostMapping
public ResponseEntity<Long> createUser(@RequestBody User user) {
Long userId = userService.createUser(user);
return ResponseEntity.ok(userId);
}
@GetMapping("/{id}")
public ResponseEntity<User> getUserById(@PathVariable Long id) {
User user = userService.getUserById(id);
return user != null ? ResponseEntity.ok(user) : ResponseEntity.notFound().build();
}
@GetMapping
public ResponseEntity<List<User>> getAllUsers() {
List<User> users = userService.getAllUsers();
return ResponseEntity.ok(users);
}
@GetMapping("/page")
public ResponseEntity<List<User>> getUsersByPage(
@RequestParam(defaultValue = "1") int page,
@RequestParam(defaultValue = "10") int size) {
List<User> users = userService.getUsersByPage(page, size);
return ResponseEntity.ok(users);
}
}
6.2 API接口列表
| HTTP方法 | URL路径 | 功能描述 | 请求参数 |
|---|---|---|---|
| GET | /api/users | 获取所有用户 | 无 |
| GET | /api/users/{id} | 根据ID获取用户 | id: 用户ID |
| POST | /api/users | 创建用户 | User对象(JSON) |
| PUT | /api/users/{id} | 更新用户 | id: 用户ID, User对象(JSON) |
| DELETE | /api/users/{id} | 删除用户 | id: 用户ID |
| GET | /api/users/page | 分页查询用户 | page: 页码, size: 页大小 |
7. 事务管理
7.1 声明式事务
@Transactional(rollbackFor = Exception.class)
public Long createUserWithTransaction(String username, String email, Integer age, boolean shouldFail) throws Exception {
User user = new User(username, email, age);
userMapper.insertUser(user);
if (shouldFail) {
throw new Exception("模拟业务异常,触发事务回滚");
}
return user.getId();
}
7.2 事务传播行为
- REQUIRED:默认传播行为,如果当前存在事务,则加入该事务
- REQUIRES_NEW:创建一个新的事务,如果当前存在事务,则把当前事务挂起
- SUPPORTS:如果当前存在事务,则加入该事务;如果当前没有事务,则以非事务的方式继续运行
- NOT_SUPPORTED:以非事务方式运行,如果当前存在事务,则把当前事务挂起
8. 监控管理
8.1 Druid监控
# Druid监控配置
spring:
datasource:
druid:
# 监控配置
web-stat-filter:
enabled: true
url-pattern: /*
exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"
stat-view-servlet:
enabled: true
url-pattern: /druid/*
reset-enable: false
login-username: admin
login-password: admin
8.2 Spring Boot Actuator
# 管理端点配置
management:
endpoints:
web:
exposure:
include: health,info,metrics,env
endpoint:
health:
show-details: always
9. 测试开发
9.1 单元测试
@SpringBootTest
@Transactional
@Rollback
class SpringBootMybatisApplicationTests {
@Autowired
private UserService userService;
@Test
void testCreateAndQueryUser() {
User user = new User();
user.setUsername("test_user");
user.setEmail("[email protected]");
user.setAge(25);
Long userId = userService.createUser(user);
assertNotNull(userId);
User foundUser = userService.getUserById(userId);
assertNotNull(foundUser);
assertEquals("test_user", foundUser.getUsername());
}
}
9.2 集成测试
@Test
void testTransactionRollback() {
try {
userService.createUserWithTransaction("rollback_user", "[email protected]", 25, true);
fail("应该抛出异常");
} catch (Exception e) {
System.out.println("事务回滚测试: " + e.getMessage());
}
// 验证用户没有被创建
User user = userService.getUserByUsername("rollback_user");
assertNull(user);
}
10. 性能优化
10.1 连接池优化
🔧 连接池配置
- 合理设置初始连接数
- 配置最大连接数
- 设置连接超时时间
- 启用连接验证
📊 监控指标
- 活跃连接数
- 连接池使用率
- SQL执行时间
- 慢查询统计
10.2 缓存配置
# MyBatis缓存配置
mybatis:
configuration:
cache-enabled: true
lazy-loading-enabled: true
aggressive-lazy-loading: false
11. 最佳实践
11.1 项目结构
- 分层架构:Controller → Service → Mapper → Entity
- 包命名:按功能模块组织包结构
- 配置管理:使用profile管理多环境配置
- 异常处理:统一异常处理和错误响应
11.2 开发建议
📝 代码规范
- 遵循RESTful API设计原则
- 使用合适的HTTP状态码
- 统一响应格式
- 添加适当的注释和文档
🔒 安全考虑
- 参数验证和SQL注入防护
- 敏感信息加密存储
- 接口权限控制
- 日志脱敏处理
12. 常见问题与解决方案
12.1 配置问题
问题:Mapper接口无法注入解决:检查@MapperScan注解配置,确保包路径正确
问题:数据源配置失败解决:检查数据库连接信息,确保驱动类路径正确
12.2 运行时问题
问题:事务不生效解决:确保@EnableTransactionManagement注解存在,方法为public
问题:SQL执行异常解决:开启SQL日志,检查生成的SQL语句是否正确
13. 实践练习
练习任务:
- 创建一个完整的用户管理REST API
- 实现用户的CRUD操作
- 添加分页查询功能
- 实现条件查询和统计功能
- 添加事务管理和异常处理
- 配置Druid监控和Actuator端点
- 编写单元测试和集成测试
- 优化性能和添加缓存
14. 运行示例
运行步骤:
- 创建数据库:CREATE DATABASE mybatis_springboot
- 执行初始化脚本:mysql -u root -p mybatis_springboot < init.sql
- 修改数据库连接配置:编辑application.yml
- 启动应用:mvn spring-boot:run
- 测试API:访问http://localhost:8080/mybatis-demo/api/users
- 查看监控:访问http://localhost:8080/mybatis-demo/druid/
- 运行测试:mvn test
💡 提示:Spring Boot与MyBatis的集成大大简化了配置工作,通过自动配置和起步依赖,可以快速构建现代化的数据访问应用。重点掌握配置管理、注解开发、事务管理和REST API设计等核心技能。
本章小结
💡 本章小结
本章我们深入学习了Spring Boot与MyBatis的整合开发。通过Spring Boot的自动配置特性,我们可以快速搭建MyBatis项目,大大简化了配置工作。同时学习了多数据源配置、事务管理等高级特性。下一章预告:我们将学习MyBatis-Plus框架,它在MyBatis基础上提供了更多便捷的功能,如代码生成器、条件构造器等,进一步提升开发效率。
下一章节 🎉
恭喜!你已完成第14章学习
你已经掌握了 Spring Boot 与 MyBatis 整合开发,准备好学习下一章了吗?
第15章