目录
Spring Boot 整合 MyBatis 全流程指南
一、整合回顾与准备
(一)Spring 整合 MyBatis 回顾
(二)Spring Boot 整合 MyBatis 优势
(三)案例需求
(四)准备数据库
二、创建工程并引入依赖
三、配置数据源信息
四、编写代码
(一)引入实体类
(二)创建 mapper 接口
(三)创建 service 接口及实现类
(四)创建 controller 类
五、测试工程
在实际开发中,配置文件的使用至关重要。本文将通过一个案例详细讲解 Spring Boot 整合 MyBatis 的过程,包括整合步骤、代码编写以及配置文件的使用,同时展示 Spring Boot 起步依赖和自动配置带来的便捷之处。
使用 Spring 整合 MyBatis 时,需要引入 MyBatis 依赖以及 MyBatis 和 Spring 的整合依赖。依赖导入后,还需配置一系列 bean 对象,如 SqlSessionFactoryBean、MapperScannerConfigurer 和 DataSource 等,配置完成才算整合成功。
使用 Spring Boot 整合 MyBatis 时,只需引入 MyBatis 的起步依赖,其内部包含了 MyBatis 依赖及整合依赖。同时,起步依赖会自动将一些 bean 对象注入到 IOC 容器,无需手动配置。但仍需在配置文件中进行数据库相关配置,如驱动、连接、用户名和密码等。
本次案例需查询 user 表中指定 id 的数据,并将查询结果响应给浏览器。
org.mybatis.spring.boot
mybatis-spring-boot-starter
3.0.0
mysql
mysql-connector-java
引入依赖后,记得刷新项目。
在配置文件(application.properties 或 application.yml)中配置数据源信息:
# application.properties
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/MYB
spring.datasource.username=root
spring.datasource.password=1234
注意:username 和 password 需根据实际情况配置为自己的账号密码。
将 user.java 实体类引入工程,其成员变量与数据库表字段一一对应。
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
@Mapper
public interface UserMapper {
@Select("select * from user where id = #{id}")
User findById(Integer id);
}
public interface UserService {
User findById(Integer id);
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User findById(Integer id) {
return userMapper.findById(id);
}
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/findById")
public User findById(Integer id) {
return userService.findById(id);
}
}
启动工程,在浏览器中访问指定路径(如localhost:8080/findById?id=1),查询结果应与数据库中数据一致,说明整合成功。
通过以上步骤,我们完成了 Spring Boot 整合 MyBatis 的过程。在实际开发中,Spring Boot 的自动配置功能大大简化了开发流程,让我们能够更专注于业务代码的编写。希望本文对您有所帮助,如有疑问,欢迎留言交流。