目录
快速开始:
快速开始需要做的事情:
测试BaseMapper中的方法:
思考:
MyBatis优点:
日志处理:
主键生成策略:
最新的官方主键策略:
在实体类中标注主键生成策略:
package com.fan.entity;
import java.io.Serializable;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
/**
* <p>
*
* </p>
*
* @author fan
* @since 2021-05-07
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("user")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "id",type = IdType.AUTO)//数据库自增策略
private Integer id;
private String name;
private Integer age;
private String email;
}
CURD的插入:
package com.fan;
import com.fan.entity.User;
import com.fan.mapper.UserMapper;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import javax.annotation.Resource;
import java.util.List;
import java.util.UUID;
@SpringBootTest
class SpringbootUserTests {
@Resource
private UserMapper userMapper;
@Test
public void test01(){
List<User> users = userMapper.selectList(null);
users.forEach(System.out::println);
}
@Test
public void testInsert(){
for (int i = 0; i < 10 ; i++) {
User user = new User();
user.setAge(18);
user.setName(UUID.randomUUID().toString().substring(0,5));
user.setEmail(UUID.randomUUID().toString().substring(2,5)+"@qq.com");
int insert = userMapper.insert(user);
System.out.println(insert);
System.out.println(user);//主键自动回填到实体类中。MP自动帮我们完成的。
}
}
}
CURD的更新:
自动填充(时间字段)
:
总结:两步走:
第一步,数据库字段添加创建时间和更新时间字段,然后在实体类中添加时间对应的属性,并( 注意!这里需要标记为填充字段)在其上设置 @TableField(fill = FieldFill.INSERT)等
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.UPDATE)
private Date updateTime;
第二步:自定义实现类 MyMetaObjectHandler
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
log.info("start insert fill ....");
this.setFieldValByName("createTime",new Date(),metaObject);
this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now()); // 起始版本 3.3.0(推荐使用)
// 或者
//this.strictUpdateFill(metaObject, "createTime", () -> LocalDateTime.now(), LocalDateTime.class); // 起始版本 3.3.3(推荐)
}
@Override
public void updateFill(MetaObject metaObject) {
log.info("start update fill ....");
this.setFieldValByName("updateTime",new Date(),metaObject);
this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now()); // 起始版本 3.3.0(推荐)
// 或者
//this.strictUpdateFill(metaObject, "updateTime", () -> LocalDateTime.now(), LocalDateTime.class); // 起始版本 3.3.3(推荐)
}
}
r然后测试跟新和插入,查看数据库。
乐观锁:
OptimisticLockerInnerInterceptor
当要更新一条记录的时候,希望这条记录没有被别人更新
乐观锁实现方式:
取出记录时,获取当前version
更新时,带上这个version
执行更新时, set version = newVersion where version = oldVersion
如果version不对,就更新失败
第一步:给数据库增加version字段
第二步: 给实体类加对应的字段
@Version//MP的乐观锁
private Integer version;
第三步:注册组件:
说明:
支持的数据类型只有:int,Integer,long,Long,Date,Timestamp,LocalDateTime
整数类型下 newVersion = oldVersion + 1
newVersion 会回写到 entity 中
仅支持 updateById(id) 与 update(entity, wrapper) 方法
在 update(entity, wrapper) 方法下, wrapper 不能复用!!!
查询操作:
分页查询:
第一步分页插件的编写:
//Spring boot方式
@Configuration
@MapperScan("com.baomidou.cloud.service.*.mapper*")
public class MybatisPlusConfig {
// 旧版
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
// 设置请求的页面大于最大页后操作, true调回到首页,false 继续请求 默认false
// paginationInterceptor.setOverflow(false);
// 设置最大单页限制数量,默认 500 条,-1 不受限制
// paginationInterceptor.setLimit(500);
// 开启 count 的 join 优化,只针对部分 left join
paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
return paginationInterceptor;
}
// 最新版
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.H2));
return interceptor;
}
}
第二步:测试:
删除操作:
代码演示:
@Test
public void testDel(){
int i = userMapper.deleteById(31);
int i1 = userMapper.deleteBatchIds(Arrays.asList(30, 29));
HashMap<String, Object> map = new HashMap<>();
map.put("name","22e87");
int i2 = userMapper.deleteByMap(map);
}
逻辑删除
第一步:在数据库增加一个字段deleted字段,默认值为0,0代表没有被删除,1代表被删除。
第二步:实体类中增加属性:
// 逻辑删除标识(0.未删除,1.已删除)
// 下面注解只对当前实体有限,局部的,一般都采用全局策略设置在yml中,怕乱了
// @TableLogic(value = “逻辑未删除”,delval = “逻辑已删除”)
@TableLogic
private int deleted;
第三步:配置(新的版本不需要注入组件@Bean)
// 3.1.1以下版本需要此配置,以上版本不需要此配置
// @Bean
// public ISqlInjector sqlInjector(){
// return new LogicSqlInjector();
// }
配置方式:
例: application.yml
mybatis-plus:
global-config:
db-config:
logic-delete-field: flag # 全局逻辑删除的实体字段名(since 3.3.0,配置后可以忽略不配置步骤2,步骤2: 实体类字段上加上@TableLogic注解)
logic-delete-value: 1 # 逻辑已删除值(默认为 1)
logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)
测试:逻辑删除实际上执行的是跟新操作,将删除标志设置为1(删除状态)
,当我们再次查询的时候,系统查询的方法自动帮我们拼接上 WHERE deleted=0(查询未被删除的)
拓展:
(1)优化
查询语句时,sql中不显示逻辑删除标识deleted字段
1.在字段上添加注解@TableField(select = false)
@TableLogic
// 查询时,查询sql语句中不显示此删除标识字段
@TableField(select = false)
private int deleted;
测试:
// SELECT id,name,age,email,manager_id,create_time,update_time,version,deleted FROM user WHERE deleted=0
// SELECT id,name,age,email,manager_id,create_time,update_time,version FROM user WHERE deleted=0
@Test
public void select() {
List<User> list = userMapper.selectList(null);
list.forEach(System.out::println);
}
(2)自定义的语句不会自动添加逻辑删除限定(即WHERE deleted=0)
针对上面自定义方法不会自动添加限定条件的情况,针对两种场景下的解决办法:
1.场景一是自己手动在代码的Wrapper中加上这个过滤条件:
// select * from user WHERE (age > ?)
// select * from user WHERE (age > ? AND deleted = ?)
@Test
public void mySelect() {
List<User> list = userMapper.mySelectList(
Wrappers.<User>lambdaQuery().gt(User::getAge,25).eq(User::getDeleted,0));
list.forEach(System.out::println);
}
2.还有一种场景是,没有使用Wrapper的自定义sql语句,可以把限定条件写在sql语句中,这里要特别注意下。
性能分析插件
该功能在3.2.0版本被废除,3.2.0以上版本可以使用性能分析打印插件,3.2.0以下版本可以接着使用
在配置类中配置插件:
@Bean
@Profile({"dev","test"}) // 指定环境
public PerformanceInterceptor performanceInterceptor() {
PerformanceInterceptor interceptor = new PerformanceInterceptor();
// sql美化打印
interceptor.setFormat(true);
// 设置SQL超时时间
interceptor.setMaxTime(500);
//格式化语句
performanceInterceptor.setFormat(true);
return interceptor;
}
从以上代码中可以看出需要设置执行的环境
在application.yml中配置
profiles:
active: dev #设置当前环境为dev
3.2.0以上版本可以使用性能分析打印插件
性能分析打印:
引入依赖:
<dependency>
<groupId>p6spy</groupId>
<artifactId>p6spy</artifactId>
<version>3.8.7</version>
</dependency>
增加spy.properties配置文件:
#3.2.1以上使用
modulelist=com.baomidou.mybatisplus.extension.p6spy.MybatisPlusLogFactory,com.p6spy.engine.outage.P6OutageFactory
#3.2.1以下使用或者不配置
#modulelist=com.p6spy.engine.logging.P6LogFactory,com.p6spy.engine.outage.P6OutageFactory
# 自定义日志打印
logMessageFormat=com.baomidou.mybatisplus.extension.p6spy.P6SpyLogger
#日志输出到控制台
appender=com.baomidou.mybatisplus.extension.p6spy.StdoutLogger
# 使用日志系统记录 sql
#appender=com.p6spy.engine.spy.appender.Slf4JLogger
# 设置 p6spy driver 代理
deregisterdrivers=true
# 取消JDBC URL前缀
useprefix=true
# 配置记录 Log 例外,可去掉的结果集有error,info,batch,debug,statement,commit,rollback,result,resultset.
excludecategories=info,debug,result,commit,resultset
# 日期格式
dateformat=yyyy-MM-dd HH:mm:ss
# 实际驱动可多个
#driverlist=org.h2.Driver
# 是否开启慢SQL记录
outagedetection=true
# 慢SQL记录标准 2 秒
outagedetectioninterval=2
application.yml 配置:
spring:
datasource:
driver-class-name: com.p6spy.engine.spy.P6SpyDriver
type: com.alibaba.druid.pool.DruidDataSource
url: jdbc:p6spy:mysql://localhost:3306/ssm?
username: username
password: password
注意!
driver-class-name 为 p6spy 提供的驱动类
url 前缀为 jdbc:p6spy 跟着冒号为对应数据库连接地址
打印出sql为null,在excludecategories增加commit
批量操作不打印sql,去除excludecategories中的batch
批量操作打印重复的问题请使用MybatisPlusLogFactory (3.2.1新增)
该插件有性能损耗,不建议生产环境使用
条件构造器:
模糊查询:
子查询:
排序测试:
MP的全局配置:
mybatis-plus:
global-config:
db-config:
id-type: auto #主键策略,mysql是采取自增的
configuration:
map-underscore-to-camel-case: true #可以不用配置,默认就是配置了true
其中:camel:骆驼
通用更新操作:
int updateById(@Param(“et”) T entity);
自动代码生成工具类:
package com.fan.generator;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
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 com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import java.util.ArrayList;
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();
//获取用户的目录
final String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor("fan");
gc.setBaseResultMap(true);
gc.setBaseColumnList(true);
// 是否打开输出目录 默认为true
gc.setOpen(false);
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/test?allowMultiQueries=true&useSSL=false&serverTimezone=UTC");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("root");
mpg.setDataSource(dsc);
// 包配置
final PackageConfig pc = new PackageConfig();
// pc.setModuleName(scanner("模块名"));
pc.setParent("com.fan");
pc.setEntity("entity");//设置实体类包
/* pc.setMapper("mapper");
pc.setService("service");
pc.setController("controller");*/
mpg.setPackageInfo(pc);
// 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
// 如果模板引擎是 freemarker
String templatePath = "/templates/mapper.xml.ftl";
// 如果模板引擎是 velocity
// String templatePath = "/templates/mapper.xml.vm";
// 自定义输出配置
List<FileOutConfig> focList = new ArrayList<FileOutConfig>();
// 自定义配置会被优先输出
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
return projectPath + "/src/main/resources/mapper/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
// 配置自定义输出模板
// 指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
// templateConfig.setEntity("templates/entity2.java");
// templateConfig.setService();
// templateConfig.setController();
templateConfig.setXml(null);
mpg.setTemplate(templateConfig);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
//默认支持驼峰名称
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
// strategy.setSuperEntityClass("com.fame.common.BaseEntity");
strategy.setEntityLombokModel(true);//自动lombok
strategy.setLogicDeleteFieldName("deleted");//逻辑删除字段
//自动填充
TableFill createTime = new TableFill("createTime", FieldFill.INSERT);
TableFill updateTime = new TableFill("updateTime", FieldFill.UPDATE);
ArrayList<TableFill> tableFills = new ArrayList<>();
tableFills.add(createTime);
tableFills.add(updateTime);
strategy.setTableFillList(tableFills);
//乐观锁
strategy.setVersionFieldName("version");
strategy.setRestControllerStyle(true);//restful风格的支持
// strategy.setSuperControllerClass("com.fame.common.BaseController");
strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
strategy.setSuperEntityColumns("id");
// strategy.setControllerMappingHyphenStyle(true);
strategy.setTablePrefix("sys");
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
}