MyBatis 入门到精通(Spring Boot 集成版)
一、概述
1.1 什么是 MyBatis?
MyBatis 是一个 持久层框架,用于简化 Java 与数据库的交互。其核心功能包括:
- 自动将数据库记录映射为 Java 对象(如
User、Order) - 通过 SQL 语句操作数据库,无需手动管理 JDBC 连接
- 支持灵活的 SQL 自定义和动态拼接
1.2 为什么选择 MyBatis?
| 优势 | 说明 |
|---|---|
| 简化开发 | 相比 JDBC 减少 80% 的模板代码 |
| SQL 解耦 | SQL 与 Java 代码分离,便于维护 |
| 灵活控制 | 支持复杂查询、动态 SQL 和自定义映射 |
| 高性能 | 直接使用原生 SQL,执行效率高 |
二、Spring Boot 集成 MyBatis
2.1 添加依赖(pom.xml)
xml
<!-- MyBatis Spring Boot Starter -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.3.0</version>
</dependency>
<!-- MySQL 驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- 数据库连接池(可选) -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.8</version>
</dependency>2.2 配置数据库连接(application.yml)
yaml
spring:
datasource:
url: jdbc:mysql://localhost:3306/mybatis_demo?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
mapper-locations: classpath:mapper/*.xml # XML 映射文件路径
type-aliases-package: com.example.demo.entity # 实体类包路径
configuration:
map-underscore-to-camel-case: true # 开启字段名自动映射(下划线转驼峰)
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 打印 SQL 日志三、核心组件开发
3.1 实体类(Entity)
java
package com.example.demo.entity;
public class User {
private Long id;
private String userName; // 对应数据库字段 user_name
private Integer age;
private String email;
// Getter & Setter
}3.2 Mapper 接口
java
package com.example.demo.mapper;
import com.example.demo.entity.User;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface UserMapper {
int insert(User user);
User selectById(Long id);
List<User> selectAll();
// 其他方法...
}3.3 Mapper XML 文件(src/main/resources/mapper/UserMapper.xml)
xml
<mapper namespace="com.example.demo.mapper.UserMapper">
<resultMap id="BaseResultMap" type="User">
<id column="id" property="id"/>
<result column="user_name" property="userName"/>
<result column="age" property="age"/>
<result column="email" property="email"/>
</resultMap>
<insert id="insert">
INSERT INTO user (user_name, age, email)
VALUES (#{userName}, #{age}, #{email})
</insert>
<select id="selectById" resultMap="BaseResultMap">
SELECT * FROM user WHERE id = #{id}
</select>
<!-- 其他 SQL -->
</mapper>3.4 Service 层
java
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User getUserById(Long id) {
return userMapper.selectById(id);
}
// 其他业务方法...
}3.5 Controller 层
java
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/{id}")
public User getUser(@PathVariable Long id) {
return userService.getUserById(id);
}
// 其他接口...
}3.6 启动类配置
java
@SpringBootApplication
@MapperScan("com.example.demo.mapper") // 扫描 Mapper 包
public class MyBatisDemoApplication {
public static void main(String[] args) {
SpringApplication.run(MyBatisDemoApplication.class, args);
}
}四、高级功能
4.1 动态 SQL
| 标签 | 作用 | 示例 |
|---|---|---|
<if> | 条件判断 |
xml
<if test="name != null">
AND user_name LIKE '%${name}%'
</if>| <where> | 自动处理 WHERE 条件 |
xml
<where>
<if test="age != null">AND age = #{age}</if>
</where>| <foreach> | 批量操作 |
xml
<foreach collection="ids" item="id" open="(" separator="," close=")">
#{id}
</foreach>4.2 分页插件(PageHelper)
- 配置插件
java
@Configuration
public class MyBatisConfig {
@Bean
public PageInterceptor pageInterceptor() {
return new PageInterceptor();
}
}- 使用分页
java
public List<User> getUsers(int pageNum, int pageSize) {
PageHelper.startPage(pageNum, pageSize);
return userMapper.selectAll();
}五、常见问题
5.1 Mapper 接口无法注入
- ✅ 检查
@Mapper注解或@MapperScan包路径 - ✅ 确保 Mapper 接口与 XML 的
namespace一致
5.2 字段映射失败
- ✅ 开启
map-underscore-to-camel-case自动映射 - ✅ 或手动配置
<resultMap>
5.3 SQL 参数绑定错误
- ✅ 单参数直接使用
#{参数名} - ✅ 多参数需用
@Param注解指定名称
六、完整 CRUD 示例
| 操作 | HTTP 方法 | URL | 示例参数 |
|---|---|---|---|
| 新增 | POST | /user |
json
{
"userName": "张三",
"age": 20,
"email": "zhangsan@example.com"
}| 查询 | GET | /user/1 | - | | 更新 | PUT | /user |
json
{
"id": 1,
"age": 21
}| 删除 | DELETE | /user/1 | - | | 模糊查询 | GET | /user/like/张 | - | | 范围查询 | GET | /user/age?minAge=18&maxAge=30 | - |
七、学习路线建议
- 基础阶段
- 掌握 XML 配置与 SQL 映射
- 理解 Mapper 接口与 XML 的绑定关系
- 进阶阶段
- 学习动态 SQL 标签(
<if>、<foreach>等) - 实践分页、批量操作、事务管理
- 学习动态 SQL 标签(
- 实战阶段
- 结合 Spring Boot 完整项目开发
- 优化 SQL 性能与结果集映射
通过以上步骤,开发者可快速构建基于 Spring Boot 的 MyBatis 应用,实现高效的数据访问层开发!