本文将演示如何在Spring Boot项目中整合MyBatis-Plus框架,快速实现数据库的增删改查操作。相较于原生MyBatis,MyBatis-Plus提供了更简洁的API和自动化功能。
环境准备
- JDK 1.8+
- MySQL 5.7+
- Spring Boot 2.7.x
- MyBatis-Plus 3.5.x
实现步骤
1. 创建项目并添加依赖
通过Spring Initializr创建项目时勾选:
- Spring Web
- MySQL Driver
手动添加MyBatis-Plus依赖(pom.xml
):
<dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.5.3.1</version>
</dependency>
2. 配置数据库连接(application.yml)
spring:datasource:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/mp_demo?useSSL=false&serverTimezone=Asia/Shanghaiusername: rootpassword: 123456mybatis-plus:configuration:log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 开启SQL日志global-config:db-config:id-type: assign_id # 主键生成策略(使用雪花算法)
3. 创建实体类
@Data
@TableName("t_user") // 指定表名
public class User {@TableId(type = IdType.ASSIGN_ID) // 雪花算法生成IDprivate Long id;private String username;private Integer age;private String email;
}
4. 创建Mapper接口
@Mapper
public interface UserMapper extends BaseMapper<User> {// 继承BaseMapper后已包含基础CRUD方法
}
5. 实现Service层(可选增强)
@Service
public class UserService {@Autowiredprivate UserMapper userMapper;// 插入public int addUser(User user) {return userMapper.insert(user);}// 查询全部public List<User> getAllUsers() {return userMapper.selectList(null);}// 条件查询public User getUserById(Long id) {return userMapper.selectById(id);}// 更新public int updateUser(User user) {return userMapper.updateById(user);}// 删除public int deleteUser(Long id) {return userMapper.deleteById(id);}
}
6. 添加分页插件配置
@Configuration
public class MybatisPlusConfig {@Beanpublic MybatisPlusInterceptor mybatisPlusInterceptor() {MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));return interceptor;}
}
7. 创建Controller
@RestController
@RequestMapping("/user")
public class UserController {@Autowiredprivate UserService userService;@PostMappingpublic String add(@RequestBody User user) {userService.addUser(user);return "插入成功";}@GetMapping("/{id}")public User getById(@PathVariable Long id) {return userService.getUserById(id);}@GetMapping("/list")public List<User> list() {return userService.getAllUsers();}@PutMappingpublic String update(@RequestBody User user) {userService.updateUser(user);return "更新成功";}@DeleteMapping("/{id}")public String delete(@PathVariable Long id) {userService.deleteUser(id);return "删除成功";}
}
测试示例
插入数据(POST /user)
{"username": "张三","age": 25,"email": "zhangsan@example.com"
}
分页查询(需自定义方法)
// 在Mapper中添加:
@Select("SELECT * FROM t_user WHERE age > #{age}")
Page<User> selectPageByAge(Page<User> page, @Param("age") Integer age);// Controller调用:
@GetMapping("/page")
public Page<User> page(@RequestParam(defaultValue = "1") Integer pageNum,@RequestParam(defaultValue = "10") Integer pageSize) {Page<User> page = new Page<>(pageNum, pageSize);return userMapper.selectPage(page, null);
}
关键特性说明
- 自动生成SQL:无需编写XML文件,基础CRUD自动实现
- 主键策略:支持
AUTO
(数据库自增)、ASSIGN_ID
(雪花算法)、UUID
等 - 条件构造器:通过
QueryWrapper
构建复杂查询条件QueryWrapper<User> wrapper = new QueryWrapper<>(); wrapper.like("username", "张").lt("age", 30); userMapper.selectList(wrapper);
常见问题排查
-
启动时报错找不到Mapper
- 确保启动类添加
@MapperScan("com.example.mapper")
- 检查Mapper接口是否标注
@Mapper
注解
- 确保启动类添加
-
字段映射失败
- 检查数据库字段名是否符合驼峰转下划线规则
- 使用
@TableField(value = "db_column")
指定字段映射
-
分页失效
- 确认已添加分页插件配置
- 查询方法参数必须为
Page
对象
扩展建议
- 使用代码生成器快速生成Entity/Mapper/Service代码
- 结合
LambdaQueryWrapper
实现类型安全的查询条件 - 通过
@Version
实现乐观锁功能