Spring-Boot-MyBatis-Plus插件

快速开始

MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

添加依赖

1
2
3
4
5
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.7.1</version>
</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
2
3
4
5
6
7
8
9
@SpringBootApplication
@MapperScan("com.baomidou.mybatisplus.samples.quickstart.mapper")
public class Application {

public static void main(String[] args) {
SpringApplication.run(QuickStartApplication.class, args);
}

}

实体类

编写实体类 User.java(此处使用了 Lombok 简化代码和TableName来注明表名称)

1
2
3
4
5
6
7
8
@TableName("t_user")
@Data
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}

编写Mapper类 UserMapper.java 并继承 BaseMapper UserMapper接口中可以直接写查询sql语句
也可以使用继承来的查询方法

1
2
3
4
public interface UserMapper extends BaseMapper<User> {
@Select("select * from t_User where username = #{username}")
UserDO getByUsername(String username);
}

测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@RunWith(SpringRunner.class)
@SpringBootTest
public class SampleTest {

@Autowired
private UserMapper userMapper;

@Test
public void testSelect() {
System.out.println(("----- selectAll method test ------"));
List<User> userList = userMapper.selectList(null);
Assert.assertEquals(5, userList.size());
userList.forEach(System.out::println);
}

}

小结

通过以上几个简单的步骤,我们就实现了 User 表的 CRUD 功能,甚至连 XML 文件都不用编写!
从以上步骤中,我们可以看到集成MyBatis-Plus非常的简单,只需要引入 starter 工程,并配置 mapper 扫描路径即可。
同时MyBatis-Plus也提供分页查询以及自定义扩展的接口,但是由于是开源的框架,作者好像完全没有考虑到兼容性,导致后面的升级十分困难。