文章目录
- 1. 简介
- 1.1 特性
- 2. 自己使用过程遇到的补充
- 2.1 aplication.properties配置
- 2.2 mybatis-plus默认开启驼峰命名
- 2.3 自定义方法和使用自定义xml
- **2.4 代码生成器**
- 2.4.1 依赖引入
- 2.4.2 编写配置
- 2.4.3 运行自动代码生成
- mapper接口扫描和xml文件扫描配置(踩坑 IDEA默认是不解析xml的)
1. 简介
MyBatis-Plus官网
MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
1.1 特性
- 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
- 损耗小:启动即会自动注入基本 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 操作智能分析阻断,也可自定义拦截规则,预防误操作
2. 自己使用过程遇到的补充
基本的使用请详见官网教程。
2.1 aplication.properties配置
# Mysql 数据库
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# 日志配置
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
# 服务器端口
server.port=6666
2.2 mybatis-plus默认开启驼峰命名
当我们在数据库中表中使用下划线时,会自动转成驼峰命名。(即从经典数据库列名 A_COLUMN(下划线命名) 到经典 Java 属性名 aColumn(驼峰命名) 的类似映射)
对应实体类为:
测试:
@Test
void testSelect(){
List<User> users = this.userMapper.selectList(null);
users.forEach(System.out::println);
}
结果:自动开启驼峰命名转换
JDBC Connection [HikariProxyConnection@982313508 wrapping com.mysql.cj.jdbc.ConnectionImpl@1eb9a3ef] will not be managed by Spring
==> Preparing: SELECT id,name,age,email,gmt_create,gmt_modified FROM user
==> Parameters:
<== Columns: id, name, age, email, gmt_create, gmt_modified
<== Row: 1, Jone, 18, test1@baomidou.com, 2021-05-26 13:27:20, 2021-05-26 13:27:23
<== Row: 2, Jack, 20, test2@baomidou.com, null, null
<== Row: 3, Tom, 28, test3@baomidou.com, null, null
<== Row: 4, Sandy, 21, test4@baomidou.com, null, null
<== Row: 5, Billie, 24, test5@baomidou.com, null, null
<== Total: 5
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@3c232051]
User(id=1, name=Jone, age=18, email=test1@baomidou.com, gmtCreate=Wed May 26 13:27:20 CST 2021, gmtModified=Wed May 26 13:27:23 CST 2021)
User(id=2, name=Jack, age=20, email=test2@baomidou.com, gmtCreate=null, gmtModified=null)
User(id=3, name=Tom, age=28, email=test3@baomidou.com, gmtCreate=null, gmtModified=null)
User(id=4, name=Sandy, age=21, email=test4@baomidou.com, gmtCreate=null, gmtModified=null)
User(id=5, name=Billie, age=24, email=test5@baomidou.com, gmtCreate=null, gmtModified=null)
如果需要关闭,则在application.properties中关闭:
# 驼峰命名
mybatis-plus.configuration.map-underscore-to-camel-case=false //默认为true
2.3 自定义方法和使用自定义xml
首先在我们的接口Mapper中自定义方法:
@Repository // 持久层
public interface UserMapper extends BaseMapper<User> {
public User findByName(String name);
}
如果需要使用xml,则可以直接在该Mapper同级目录下新建同名的xml文件,但是这样接口和xml文件都在同一个目录下。为了分离,也可以如下在resource中建立于mapper接口同名的包,在包下新建xml文件如下:
简单编写我们的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="com.example.mybatisplus.mapper.UserMapper">
<select id="findByName" parameterType="string" resultType="com.example.mybatisplus.entity.User">
select * from user where name = #{name}
</select>
</mapper>
测试
@Test
void testMyOwnSql(){
final User jone = this.userMapper.findByName("Jone");
System.out.println(jone);
}
结果:
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@4c302f38] was not registered for synchronization because synchronization is not active
JDBC Connection [HikariProxyConnection@984832924 wrapping com.mysql.cj.jdbc.ConnectionImpl@7741d346] will not be managed by Spring
==> Preparing: select * from user where name = ?
==> Parameters: Jone(String)
<== Columns: id, name, age, email, gmt_create, gmt_modified
<== Row: 1, Jone, 18, test1@baomidou.com, 2021-05-26 13:27:20, 2021-05-26 13:27:23
<== Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@4c302f38]
User(id=1, name=Jone, age=18, email=test1@baomidou.com, gmtCreate=Wed May 26 13:27:20 CST 2021, gmtModified=Wed May 26 13:27:23 CST 2021)
其实这样编译完后,还是会将mapper接口和xml整合到一起.
也可以直接在UserMapper中自定义方法上使用注解, 而不需要写xml.
@Select("select * from user where name=#{name}")
public User findByNameUserAnnotation(String name);
测试:
@Test
void testMyOwnSqlUseAnnotation(){
final User jone = this.userMapper.findByNameUserAnnotation("Jone");
System.out.println(jone);
}
结果: 同样可以.
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@ee8e7ff] was not registered for synchronization because synchronization is not active
JDBC Connection [HikariProxyConnection@530402062 wrapping com.mysql.cj.jdbc.ConnectionImpl@1e8fb66f] will not be managed by Spring
==> Preparing: select * from user where name=?
==> Parameters: Jone(String)
<== Columns: id, name, age, email, gmt_create, gmt_modified
<== Row: 1, Jone, 18, test1@baomidou.com, 2021-05-26 13:27:20, 2021-05-26 13:27:23
<== Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@ee8e7ff]
User(id=1, name=Jone, age=18, email=test1@baomidou.com, gmtCreate=Wed May 26 13:27:20 CST 2021, gmtModified=Wed May 26 13:27:23 CST 2021
同时说明 mybatis-plus 可以同时支持
使用 xml 文件配置 或者直接通过注解配置.
2.4 代码生成器
AutoGenerator 是 MyBatis-Plus 的代码生成器,通过 AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller等各个模块的代码,极大的提升了开发效率。
2.4.1 依赖引入
MyBatis-Plus 从 3.0.3
之后移除了代码生成器与模板引擎的默认依赖,需要手动添加相关依赖:
-
添加 代码生成器 依赖
<dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.4.1</version> </dependency>
-
添加 模板引擎 依赖,MyBatis-Plus 支持 Velocity(默认)、Freemarker、Beetl,用户可以选择自己熟悉的模板引擎,如果都不满足您的要求,可以采用自定义模板引擎。
Velocity(默认):
<dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity-engine-core</artifactId> <version>2.3</version> </dependency>
2.4.2 编写配置
使用模块开发:
代码自动生成类:
package com.example.mybatisplus;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import lombok.val;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class CodeGenerator {
/**
* <p>
* 读取控制台内容
* </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();
// 全局配置
GlobalConfig gc = new GlobalConfig();
// 获取当前项目的全路径 E:\IDEA-Project\SpringBoot
String projectPath = System.getProperty("user.dir");
// 生成到:E:\IDEA-Project\SpringBoot\${moduleName}\src\main\java
String moduleName = scanner("请输入模块名");
gc.setOutputDir(projectPath +"\\"+ moduleName +"\\src\\main\\java");
// 设置自动生成注释的Author
gc.setAuthor("李溪滨");
//是否打开输出目录 (默认值:true)
gc.setOpen(false);
// 开启 swagger2 模式 (默认值:false) 须添加swagger依赖
gc.setSwagger2(true);
// 是否覆盖已有文件
gc.setFileOverride(false);
// service 命名方式, 默认会以I开头(IUserService) %sService 生成 UserService
gc.setServiceName("%sService");
// 代码生成器设置全局配置
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/mybatis_plus?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8");
// dsc.setSchemaName("public");
dsc.setDriverName("com.mysql.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("root");
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setParent("com.example.mybatisplus");
pc.setEntity("entity"); //实体类包名
pc.setController("controller"); // 控制器包名
pc.setMapper("mapper"); // mapper包名
pc.setService("service"); // service包名
pc.setServiceImpl("service.impl"); // service实现类包名
mpg.setPackageInfo(pc);
// 策略配置 (数据库表配置,通过该配置,可指定需要生成哪些表或者排除哪些表)
StrategyConfig strategy = new StrategyConfig();
// 数据库表映射到实体的命名策略
strategy.setNaming(NamingStrategy.underline_to_camel);
// 数据库表字段映射到实体的命名策略, 未指定按照 naming 执行
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
// 是否为 lombok模型
strategy.setEntityLombokModel(true);
// 生成 @RestController 控制器
strategy.setRestControllerStyle(true);
// 设置逻辑删除字段名
//strategy.setLogicDeleteFieldName("deleted");
// 设置乐观锁字段名
//strategy.setVersionFieldName("version");
//需要包含的表名
strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
// 驼峰转连字符
strategy.setControllerMappingHyphenStyle(true);
// 是否生成实体时,生成字段注解
strategy.setEntityTableFieldAnnotationEnable(true);
// 自动填充
TableFill gmtCreate = new TableFill("gmt_create", FieldFill.INSERT);
TableFill gmtModified = new TableFill("gmt_modified", FieldFill.INSERT_UPDATE);
final List<TableFill> tableFills = Arrays.asList(gmtCreate, gmtModified);
strategy.setTableFillList(tableFills);
mpg.setStrategy(strategy);
// 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
// 如果模板引擎是 velocity
String templatePath = "/templates/mapper.xml.vm";
// 自定义输出配置
List<FileOutConfig> focList = new ArrayList<>();
// 自定义配置会被优先输出
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
System.out.println(projectPath +"/"+ moduleName + "/src/main/resources/mapper/"
+ tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML);
return projectPath +"/"+ moduleName + "/src/main/resources/mapper/"
+ tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
templateConfig.setXml(null);
mpg.setTemplate(templateConfig);
mpg.execute();
}
}
官网代码生成器
官网代码生成器配置
2.4.3 运行自动代码生成
请输入请输入模块名:
mybatis-plus
请输入表名,多个英文逗号分割:
user,role
17:30:36.431 [main] DEBUG com.baomidou.mybatisplus.generator.AutoGenerator - ==========================准备生成文件...==========================
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
17:30:36.838 [main] WARN org.apache.velocity.deprecation - configuration key 'file.resource.loader.unicode' has been deprecated in favor of 'resource.loader.file.unicode'
17:30:36.839 [main] WARN org.apache.velocity.deprecation - configuration key 'file.resource.loader.class' has been deprecated in favor of 'resource.loader.file.class'
E:\IDEA-Project\SpringBoot/mybatis-plus/src/main/resources/mapper/RoleMapper.xml
E:\IDEA-Project\SpringBoot/mybatis-plus/src/main/resources/mapper/UserMapper.xml
17:30:36.842 [main] DEBUG com.baomidou.mybatisplus.generator.AutoGenerator - ==========================文件生成完成!!!==========================
Process finished with exit code 0
自动代码生成结果:
其中的实体类由于自动代码生成中开启了Swagger, 因此会自动生成一些注解配置:
mapper接口扫描和xml文件扫描配置(踩坑 IDEA默认是不解析xml的)
如果不在自动生成类中配置如下:
// 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
// 如果模板引擎是 velocity
String templatePath = "/templates/mapper.xml.vm";
// 自定义输出配置
List<FileOutConfig> focList = new ArrayList<>();
// 自定义配置会被优先输出
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
System.out.println(projectPath +"/"+ moduleName + "/src/main/resources/mapper/"
+ tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML);
return projectPath +"/"+ moduleName + "/src/main/resources/mapper/"
+ tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
templateConfig.setXml(null);
mpg.setTemplate(templateConfig);
则生成xml时,会在main下的mapper包中生成一个xml包,存放mapper的XML文件.
踩坑 : 对于IDEA系列编辑器,XML 文件是不能放在 java 文件夹中的,IDEA 默认不会编译源码文件夹中的 XML 文件。
我在使用IDEA 编写Mybatis-plus时,写的自定义SQl语句总是显示 Invalid bound statement (not found) . 根据报错信息可以看到是Mapper中自己写的自定义方法 没有绑定相应的SQL语句. 检查了一遍配置,都没有问题,而Sprinboot启动时 log中Property ‘mapperLocations’ was not specified这句提示引起了我的注意 , 虽然配置中配置了mybatis-plus.mapper-locations=classpath*:/mapper/xml/*.xml,但启动器没扫描到,十分奇怪。后来才知道从Mybatis-plus 官方文档找出了答案
因为对于IDEA系列编辑器,XML 文件是不能放在 java 文件夹中的,IDEA 默认不会编译源码文件夹中的 XML 文件。
果然我在POM中没有指明解析xml, 在启动后生成的target 目录下文件的mapper包下没有找到相应的xml .
因此需要如上配置, 将生成的XML文件生成到 resource/mapper
文件下.
然后需要在 application.properties文件中配置 扫描XML 的目录.
mybatis-plus.mapper-locations=classpath*:/mapper/*.xml