SpringBoot整合Mybatis-Plus

添加依赖

引入Spring Boot Starter 父工程:

1
2
3
4
5
6
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>spring-latest-version</version>
<relativePath/>
</parent>

引入 spring-boot-starterspring-boot-starter-test 依赖:

1
2
3
4
5
6
7
8
9
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

上述过程均可通过SpringBoot快速初始化自动完成

引入mybatis-plus-boot-startermysql 依赖:

1
2
3
4
5
6
7
8
9
10
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>

当前Mybatis-Plus最新版本

配置

application.yaml 配置文件中添加mysql 数据库的相关配置:

1
2
3
4
5
6
7
# DataSource Config
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/mybatis?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=GMT%2B8
username: root
password: 123456

在 Spring Boot 启动类中添加 @MapperScan 注解,扫描 Mapper 文件夹:

1
2
3
4
5
6
7
8
9
@SpringBootApplication
@MapperScan("com.catnyan.mapper")
public class Application {

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

}

编码

编写实体类 User.java

1
2
3
4
5
6
7
@Data
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}

编写Mapper类 UserMapper.java

1
2
3
public interface UserMapper extends BaseMapper<User> {

}

开始使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@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);
}

}

TIP

UserMapper 中的 selectList() 方法的参数为 MP 内置的条件封装器 Wrapper,所以不填写就是无任何条件

控制台输出:

1
2
3
4
5
User(id=1, name=Jone, age=18, email=test1@baomidou.com)
User(id=2, name=Jack, age=20, email=test2@baomidou.com)
User(id=3, name=Tom, age=28, email=test3@baomidou.com)
User(id=4, name=Sandy, age=21, email=test4@baomidou.com)
User(id=5, name=Billie, age=24, email=test5@baomidou.com)

配置日志

1
2
3
4
5
6
7
8
9
# 方式一
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

# 方式二 application.yml 中增加配置,指定 mapper 文件所在的包
logging:
level:
com.baomidou.example.mapper: debug