SpringBoot基础之集成MybatisPlus

这是我参与11月更文挑战的第8天,活动详情查看:2021最后一次更文挑战

前言

对于Java系中,最著名的ORM框架也就是Mybatis,JPA,Hibernate了,在面对领导开发快速迭代的场景想,大部分的项目都是基于SSM的,这个M也就是Mybatis.

Mybatis简单灵活从另一个角度就是需要自己写所有的代码(简单的可以使用代码生成器),MybatisPlus就是Mybatis的增强工具,在MyBatis的基础上只做增强不做改变,为简化开发、提高效率而生。

Mybatis-Plus官网在这里

集成

这里的连接池是用的默认的HikariCP连接池,想用Druid或者只用Mybatis可以看另一篇文章

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
xml复制代码<!--mysql连接驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>

<!--Mbatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>

<!--Mbatis Plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.1.tmp</version>
</dependency>

application.yml配置

数据库和连接池配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
yaml复制代码spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver #mysql 8.0
url: jdbc:mysql:///zdc_test?useUnicode=true&characterEncoding=utf8&autoReconnect=true&rewriteBatchedStatements=TRUE&serverTimezone=GMT%2B8&useSSL=false&allowPublicKeyRetrieval=true
username: root
password: 123123
type: com.zaxxer.hikari.HikariDataSource #当前使用的数据源 Hikari
hikari:
minimum-idle: 1 # 池中维护的最小空闲连接数 默认10 根据实际情况来
maximum-pool-size: 10 # 池中最大连接数 根据实际情况来
auto-commit: true # 自动提交从池中返回的连接
idle-timeout: 600000 # 一个连接idle状态的最大时长(毫秒),超时则被释放(retired),缺省:10分钟
max-lifetime: 1800000 # 一个连接的生命时长(毫秒),超时而且没被使用则被释放(retired),缺省:30分钟,建议设置比数据库超时时长少30秒,参考MySQL
connection-timeout: 30000 # 等待连接池分配连接的最大时长(毫秒),超过这个时长还没可用的连接则发生SQLException, 缺省:30秒
connection-test-query: select 1
read-only: false # 是否是只读

MyBatis配置

mybatisPlus 配置 (官方文档:mybatis中的配置 在mybatisplus上均可配置)

1
2
3
4
5
6
7
8
yaml复制代码mybatis-plus:
mapper-locations: classpath:/mappers/*Mapper.xml
type-aliases-package: zdc.enterprise.entity
configuration:
use-generated-keys: true
global-config:
db-config:
id-type: auto # 主键自增

必要的注解配置

Application启动类上添加相关的注解

1
2
3
4
5
6
7
8
9
10
less复制代码@ComponentScan({"zdc.enterprise.*"})
@EnableTransactionManagement
@MapperScan("zdc.enterprise.mapper")
@SpringBootApplication
public class SpringBootEnterpriseApplication {

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

@EnableTransactionManagement是开启事务管理

@MapperScan是配置dao层接口文件的扫描路径,也就是和xml对应的XXMapper或者XXDao的路径

使用

项目目录结构

1637069297(1).png

(1) 在数据库中创建一个student

1
2
3
4
5
6
7
8
9
10
less复制代码CREATE TABLE `student` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`info` varchar(255) COMMENT 'zouzdc',
`del_flag` tinyint(1) DEFAULT '0',
`create_time` datetime,
`create_by` varchar(255),
`update_time` datetime ,
`update_by` varchar(255),
PRIMARY KEY (`id`)
) ;

(2) 在entity包下创建Student.java

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
42
43
44
45
ruby复制代码@Data
@NoArgsConstructor
public class Student {

/**
* id
*/
@TableId
private Long id;

/**
* 其他信息
*/
private String info;

/**
* 是否伪删除 0否 1是
*/
@TableLogic
private String delFlag;

/**
* 创建日期
*/
@TableField(fill = FieldFill.INSERT)
private Date createTime;

/**
* 创建人
*/
@TableField(fill = FieldFill.INSERT)
private String createBy;

/**
* 更新日期
*/
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;

/**
* 更新人
*/
@TableField(fill = FieldFill.INSERT_UPDATE)
private String updateBy;
}

(3) controller

studentService自带的方法演示

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
less复制代码@RestController
@RequestMapping("/student")
public class StudentController {

@Autowired(required = false)
public StudentService studentService;

@GetMapping("getById")
public R getStudentById( Student student){
//增
studentService.save(student);
//改
studentService.updateById(student);
//查
Student student = studentService.getById(student.getId());
//删
studentService.removeById(student.getId());
//列表
List<Student> zouzdc = studentService.lambdaQuery().eq(Student::getInfo, "zouzdc").list();
return R.success();
}
}

(4) service层,需要继承IService或实现ServiceImpl通用接口

service接口StudentService.java

1
2
csharp复制代码public interface StudentService extends IService<Student> {
}

service实现类StudentService.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
scala复制代码@Service
@Slf4j
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {

//可以不声明studentMapper,当前类中的baseMapper就是实际上的studentMapper
@Autowired(required = false)
private StudentMapper studentMapper;

/**
*使用MybatisPlus的默认方法
*/
public void savePlus(Student vo) {
Student one = this.getById(vo.getId());
Student student = baseMapper.selectById(vo.getId());
}
}

(4) 在Mapper层需要继承BaseMapper接口

1
2
csharp复制代码public interface StudentMapper extends BaseMapper<Student> {
}

(5)在resourcesmappers文件下创建StudentMapper.xml文件,和原生一样

1
2
3
4
5
xml复制代码<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="zdc.enterprise.mapper.StudentMapper">

</mapper>

备注

根据项目需要权衡是否移动要使用原生的MyBatis

在使用MyBatis或者使用MyBatis-Plus的时候一定要配合代码生成器使用,网上很多开源的代码生成器,也可以自己写代码模版,提高效率

如果使用IDEA的话 推荐使用free mybatis plugin或者MybatisX插件, 能将接口类和mapper文件自动关联,并可以直接跳转

更详细的使用方式看下一篇文章

1
2
3
4
arduino复制代码    作者:ZOUZDC
链接:https://juejin.cn/post/7028963866063306760
来源:稀土掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

本文转载自: 掘金

开发者博客 – 和开发相关的 这里全都有

0%