快速开始
MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
添加依赖
1 | <dependency> |
配置
在 application.yml 配置文件中添加 H2 数据库的相关配置:1
2
3
4
5
6
7
8
9# DataSource Config
spring:
datasource:
driver-class-name: org.h2.Driver
schema: classpath:db/schema-h2.sql
data: classpath:db/data-h2.sql
url: jdbc:h2:mem:test
username: root
password: test
在 Spring Boot 启动类中添加 @MapperScan 注解,扫描 Mapper 文件夹:
1 |
|
实体类
编写实体类 User.java(此处使用了 Lombok 简化代码和TableName来注明表名称)1
2
3
4
5
6
7
8"t_user") (
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
编写Mapper类 UserMapper.java 并继承 BaseMapper
也可以使用继承来的查询方法
1 | public interface UserMapper extends BaseMapper<User> { |
测试
1 | (SpringRunner.class) |
小结
通过以上几个简单的步骤,我们就实现了 User 表的 CRUD 功能,甚至连 XML 文件都不用编写!
从以上步骤中,我们可以看到集成MyBatis-Plus非常的简单,只需要引入 starter 工程,并配置 mapper 扫描路径即可。
同时MyBatis-Plus也提供分页查询以及自定义扩展的接口,但是由于是开源的框架,作者好像完全没有考虑到兼容性,导致后面的升级十分困难。