0%

【MybatisPlus】MybatisPlus入门

MybatisPlus的简单入门

1 Mybatis入门

1.1 介绍

  • Mybatis-Plus是一个Mybatis的增强工具包,只作增强不做改变,为简化开发工作、提高生产效率而生

1.2 MybatisPlus整合

  • 项目使用的是springBoot整合MybatisPlus
  • (1)数据库表与JavaBean
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 创建user表
CREATE TABLE `user` (
`id` bigint NOT NULL COMMENT '主键ID',
`name` varchar(30) DEFAULT NULL COMMENT '姓名',
`age` int DEFAULT NULL COMMENT '年龄',
`email` varchar(50) DEFAULT NULL COMMENT '邮箱',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


# 插入数据
INSERT INTO user (id, name, age, email) VALUES
(1, 'Jone', 18, 'test1@baomidou.com'),
(2, 'Jack', 20, 'test2@baomidou.com'),
(3, 'Tom', 28, 'test3@baomidou.com'),
(4, 'Sandy', 21, 'test4@baomidou.com'),
(5, 'Billie', 24, 'test5@baomidou.com');
1
2
3
4
5
6
7
@Data
public class User {
private Long id;
private String name;
private Integer age;
private String email;
}
  • (2)Pom.xml修改
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
    <!-- 引入SpringBoot框架 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.4</version>
</parent>

<dependencies>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>

<!-- SpringBoot启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>

<!-- SpringBoot单元测试 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

<!-- MybatisPlus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.2</version>
</dependency>

<!-- MySQL驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
</dependency>
</dependencies>
  • (3)application.yaml修改
1
2
3
4
5
6
7
# 配置数据源
spring:
datasource:
username: root
password: 123
url: jdbc:mysql://localhost:3306/mybatis_plus?serverTimezone=GMT%2B8
driver-class-name: com.mysql.cj.jdbc.Driver
  • (4)创建Mapper接口
1
2
3
4
//继承通用Mapper
@Mapper
public interface UserMapper extends BaseMapper<User> {
}
  • (5)SpringBoot主启动类
1
2
3
4
5
6
@SpringBootApplication
public class MPRun {
public static void main(String[] args) {
SpringApplication.run(MPRun.class, args);
}
}
  • (6)测试
1
2
3
4
5
6
7
8
9
10
11
12
@SpringBootTest
public class SpringMPTest {

@Autowired
private UserMapper userMapper;

@Test
public void mpTest1() {
List<User> users = userMapper.selectList(null);
users.forEach(System.out::println);
}
}