效率利器:SpringBoot整合Mybatis-Plus

一、什么是Mybatis-Plus

官网地址:baomidou.com/

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

特性

  • 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
  • 损耗小:启动即会自动注入基本 CURD,性能基本无损耗,直接面向对象操作
  • 强大的 CRUD 操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分 CRUD 操作,更有强大的条件构造器,满足各类使用需求
  • 支持 Lambda 形式调用:通过 Lambda 表达式,方便的编写各类查询条件,无需再担心字段写错
  • 支持主键自动生成:支持多达 4 种主键策略(内含分布式唯一 ID 生成器 - Sequence),可自由配置,完美解决主键问题
  • 支持 ActiveRecord 模式:支持 ActiveRecord 形式调用,实体类只需继承 Model 类即可进行强大的 CRUD 操作
  • 支持自定义全局通用操作:支持全局通用方法注入( Write once, use anywhere )
  • 内置代码生成器:采用代码或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller 层代码,支持模板引擎,更有超多自定义配置等您来使用
  • 内置分页插件:基于 MyBatis 物理分页,开发者无需关心具体操作,配置好插件之后,写分页等同于普通 List 查询
  • 分页插件支持多种数据库:支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer 等多种数据库
  • 内置性能分析插件:可输出 Sql 语句以及其执行时间,建议开发测试时启用该功能,能快速揪出慢查询
  • 内置全局拦截插件:提供全表 delete 、 update 操作智能分析阻断,也可自定义拦截规则,预防误操作

二、简单的使用案例

​ 只需要添加Mybatis-Plus依赖(无需添加mybatis依赖,mybatis-plus的依赖已经包含),编写表映射的实体类和Mapper语句(继承BaseMapper)即可实现对数据库的访问,BaseMapper已经包含了基本的sql方法,无需编写Mapper.xml。

数据库表结构

1
2
3
4
5
6
7
8
9
10
sql复制代码CREATE TABLE `user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`avatar` varchar(200) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
`email` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`name` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`password` varchar(300) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
`username` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
PRIMARY KEY (`id`) USING BTREE,
UNIQUE KEY `UK_ob8kqyqqgmefl0aco34akdtpe` (`email`) USING BTREE
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;
  1. 引入依赖

  • 引入Springboot Starter 父工程
1
2
3
4
5
6
xml复制代码    <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.8</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
  • 引入依赖

只需要引入Spring Boot、MyBatis-Plus、数据库(Mysql)依赖。

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
xml复制代码        <!-- springboot -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- mybatis-plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.1</version>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.10</version>
</dependency>
  • 完整依赖文件
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
46
47
48
49
xml复制代码<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.8</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<modelVersion>4.0.0</modelVersion>

<artifactId>spring-mybatis-plus</artifactId>

<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>

<dependencies>
<!-- springboot -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- mybatis-plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.1</version>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.10</version>
</dependency>
</dependencies>
</project>
  1. 实体类

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
arduino复制代码@Data
@Accessors(chain = true)
public class User implements Serializable {
/**
* id
* */
private Integer id;
/**
* 头像
* */
private String avatar;
/**
* 邮箱
* */
private String email;
/**
* 账号
* */
private String name;
/**
* 密码
* */
private String password;
/**
* 用户名
* */
private String username;
}
  1. UserMapper

​ 这里需要继承BaseMapper接口,BaseMapper提供的

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
java复制代码public interface BaseMapper<T> extends Mapper<T> {
//插入
int insert(T entity);

//通过主键删除
int deleteById(Serializable id);
//通过Map字段对应值删除
int deleteByMap(@Param("cm") Map<String, Object> columnMap);
//通过条件Wrapper删除
int delete(@Param("ew") Wrapper<T> wrapper);
//批量删除
int deleteBatchIds(@Param("coll") Collection<? extends Serializable> idList);

//更新 通过ID匹配
int updateById(@Param("et") T entity);
//更新 通过更新条件匹配
int update(@Param("et") T entity, @Param("ew") Wrapper<T> updateWrapper);

//查询通过主键
T selectById(Serializable id);
//查询通过批量
List<T> selectBatchIds(@Param("coll") Collection<? extends Serializable> idList);
//查询通过Map
List<T> selectByMap(@Param("cm") Map<String, Object> columnMap);
//通过查询条件构造器查询,返回实体
T selectOne(@Param("ew") Wrapper<T> queryWrapper);
//通过查询条件构造器查询行数
Integer selectCount(@Param("ew") Wrapper<T> queryWrapper);
//通过查询条件构造器
List<T> selectList(@Param("ew") Wrapper<T> queryWrapper);

List<Map<String, Object>> selectMaps(@Param("ew") Wrapper<T> queryWrapper);

List<Object> selectObjs(@Param("ew") Wrapper<T> queryWrapper);
//分页查询
<E extends IPage<T>> E selectPage(E page, @Param("ew") Wrapper<T> queryWrapper);

<E extends IPage<Map<String, Object>>> E selectMapsPage(E page, @Param("ew") Wrapper<T> queryWrapper);
}

​ UserMapper.java基础了BaseMapper,如果启动类使用了MapperScan注解扫描到Mapper所在的路径可以不用使用@Mapper。

1
2
3
4
java复制代码@Mapper
public interface UserMapper extends BaseMapper<User> {

}

​ 启动类@MapperScan("com.stopping.mapper")

1
2
3
4
5
6
7
java复制代码@SpringBootApplication
@MapperScan("com.stopping.mapper")
public class MybatisPlusApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisPlusApplication.class,args);
}
}
  1. 配置文件

​ 配置数据源信息

1
2
3
4
5
6
yml复制代码spring:
datasource:
password: root
username: root
url: jdbc:mysql://localhost:3306/test?characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver
  1. 测试

1
2
3
4
5
6
7
8
9
java复制代码@SpringBootTest(classes = MybatisPlusApplication.class)
class UserMapperTest {
@Resource
private UserMapper userMapper;
@Test
public void selectUser(){
userMapper.selectList(null).stream().forEach(System.out::println);
}
}

结果

1
2
3
less复制代码User(id=1, avatar=null, email=1064076070@qq.com, name=stopping, password=$2a$10$HMoRS.lxhl0mQ1D0uKVeFeMl7nQ1ZykhI/8N3z0AiND1HUMNCZk/y, username=admin)
User(id=2, avatar=null, email=1111@cc.com, name=tom, password=123456, username=tom)
User(id=3, avatar=null, email=1123@cc.com, name=job, password=123456, username=job)

三、代码生成器

​ AutoGenerator 是 MyBatis-Plus 的代码生成器,通过 AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各个模块的代码。

​ 通过数据库链接反向生成数据库映射的实体类,以及 Entity、Mapper、Mapper XML、Service、Controller 。这些生成文件存在在什么路径都是可以通过配置实现的。

  1. 新增依赖

​ MyBatis-Plus 从 3.0.3 之后移除了代码生成器与模板引擎的默认依赖,需要手动添加相关依赖

1
2
3
4
5
6
7
8
9
10
xml复制代码<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.3.1</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.31</version>
</dependency>
  1. 使用代码生成器生成

​ 现在通过代码生成器生成Test数据库中的category表相关的代码

1
2
3
4
5
6
7
8
sql复制代码CREATE TABLE `category` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`create_time` datetime DEFAULT NULL,
`name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
`user_id` bigint(20) DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE,
KEY `FKpfk8djhv5natgshmxiav6xkpu` (`user_id`) USING BTREE
) ENGINE=MyISAM AUTO_INCREMENT=14 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;

​ 生成代码在下面,下图是生成后的代码。

image-20210628235919800

  1. 测试

1
2
3
4
5
6
7
8
9
10
11
java复制代码@SpringBootTest(classes = MybatisPlusApplication.class)
class UserMapperTest {
@Resource
private UserMapper userMapper;
@Resource
private CategoryService categoryService;
@Test
public void selectUser(){
categoryService.lambdaQuery().list().forEach(System.out::println);
}
}

结果:

1
2
3
4
5
6
7
8
9
10
11
12
ini复制代码Category(id=2, createTime=null, name=默认, userId=1)
Category(id=3, createTime=2020-08-20T01:05:05, name=计算机视觉, userId=1)
Category(id=4, createTime=2020-08-20T01:05:15, name=Spring, userId=1)
Category(id=5, createTime=2020-08-20T01:05:24, name=Mybatis, userId=1)
Category(id=6, createTime=2020-08-20T01:05:36, name=数据库, userId=1)
Category(id=7, createTime=2020-08-20T01:05:50, name=设计模式, userId=1)
Category(id=8, createTime=2020-08-20T01:13:39, name=代码编辑器, userId=1)
Category(id=9, createTime=2020-08-20T01:21:44, name=服务器, userId=1)
Category(id=10, createTime=2020-08-20T01:23:06, name=Hibernate, userId=1)
Category(id=11, createTime=2020-08-20T01:24:38, name=技术相关, userId=1)
Category(id=12, createTime=2020-08-20T03:16:06, name=前端, userId=1)
Category(id=13, createTime=2020-09-16T03:29:30, name=java, userId=1)

示例代码生成器

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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
java复制代码/**
* @Description GeneratorCode
* @Author stopping
* @date: 2021/6/28 23:33
*/
public class GeneratorCode {
/**
* 数据库连接
* */
private static final String dbUrl = "jdbc:mysql://localhost:3306/test?useUnicode=true&useSSL=false&characterEncoding=utf8";
/**
* 数据库账号
* */
private static final String username = "root";
/**
* 数据库密码
* */
private static final String password = "root";
/**
* 模块名
* */
private static final String moduleName = "/spring-mybatis-plus";

/**
* <p>
* 读取控制台内容
* @param
* </p>
*/
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("请输入" + tip + ":");
System.out.println(help.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotBlank(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("请输入正确的" + tip + "!");
}

public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
String module = scanner("请输入模块名称");
// 全局配置
GlobalConfig gc = new GlobalConfig();
//D:/code/springboot-orm/spring-mybatis-plus
String projectPath = System.getProperty("user.dir")+moduleName;
System.out.println(projectPath);
//设置文件路径和模块文件生成
gc.setOutputDir(projectPath+"/src/main/java");
gc.setAuthor("stopping");
//生成类名限制
gc.setMapperName("%sMapper");
gc.setServiceName("%sService");
gc.setServiceImplName("%sServiceImp");
gc.setControllerName("%sController");
gc.setXmlName("%sMapper");
gc.setIdType(IdType.AUTO);
gc.setOpen(false);
//是否覆盖
gc.setFileOverride(true);
//实体属性 Swagger2 注解
gc.setSwagger2(false);
mpg.setGlobalConfig(gc);

// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl(dbUrl);
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername(username);
dsc.setPassword(password);
mpg.setDataSource(dsc);

// 包配置:生成文件
PackageConfig pc = new PackageConfig();
//包路径
pc.setParent("com.stopping");
//包路径下的子包名称
pc.setMapper("mapper."+module);
pc.setController("controller."+module);
pc.setService("service."+module);
pc.setServiceImpl("service."+module+".imp");
pc.setEntity("model.entity");
pc.setXml("Mapper");
mpg.setPackageInfo(pc);

// 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};

// 如果模板引擎是 freemarker
String templatePath = "/templates/mapper.xml.ftl";

// 自定义输出配置
List<FileOutConfig> focList = new ArrayList<>();
// 自定义配置会被优先输出
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
// Mapper 文件输出
String xmlUrl = projectPath + "/src/main/resources/mapper/" + module
+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
System.out.println("xml生成路径:"+xmlUrl);
return xmlUrl;
}
});

cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);

// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
templateConfig.setXml(null);
mpg.setTemplate(templateConfig);

// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
// 写于父类中的公共字段
//strategy.setSuperEntityColumns("id");
strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
strategy.setControllerMappingHyphenStyle(true);
strategy.setTablePrefix(pc.getModuleName() + "_");
//是否生成注解
strategy.setEntityTableFieldAnnotationEnable(true);
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
}

本文转载自: 掘金

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

0%