Mybatis Plus
配置
###mybatis-plus
mybatis-plus:
configuration:
map-underscore-to-camel-case: true
auto-mapping-behavior: full
#配置日志
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
mapper-locations: classpath*:mapper/**/*Mapper.xml
#删除数据 逻辑删除 物理删除
global-config:
# 逻辑删除配置
db-config:
# 删除前
logic-not-delete-value: 1
# 删除后
logic-delete-value: 0
主键生成策略
1.执行insert插入操作时会自动生成id,默认是根据雪花算法生成
@TableId(value = "id", type = IdType.ID_WORKER) //默认
2.主键自增
首先设置数据库表字段自增
@TableId(value = "id", type = IdType.AUTO) //默认
3.其他策略
@Getter
public enum IdType {
/**
* 数据库ID自增
*/
AUTO(0),
/**
* 该类型为未设置主键类型(注解里等于跟随全局,全局里约等于 INPUT)
*/
NONE(1),
/**
* 用户自己输入ID,
* <p>该类型可以通过自己注册自动填充插件进行填充</p>
*/
INPUT(2),
/* 以下3种类型、只有当插入对象ID 为空,才自动填充。 */
/**
* 分配ID (主键类型为number或string),
* 默认实现类 {@link com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator}(雪花算法)
*
* @since 3.3.0
*/
ASSIGN_ID(3),
/**
* 分配UUID (主键类型为 string)
* 默认实现类 {@link com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator}(UUID.replace("-",""))
*/
ASSIGN_UUID(4),
/**
* @deprecated 3.3.0 please use {@link #ASSIGN_ID}
*/
@Deprecated
ID_WORKER(3),
/**
* @deprecated 3.3.0 please use {@link #ASSIGN_ID}
*/
@Deprecated
ID_WORKER_STR(3),
/**
* @deprecated 3.3.0 please use {@link #ASSIGN_UUID}
*/
@Deprecated
UUID(4);
private final int key;
IdType(int key) {
this.key = key;
}
}
自动填充
比如创建时间和修改时间等字段,通过自动化完成,不用手动更新
方式一:数据库级别
数据库表字段设置根据当前时间更新
方式二:代码级别
1.实体类字段加注解
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
2.编写处理器处理注解
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
log.info("start insert fill ....");
this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now()); // 起始版本 3.3.0(推荐使用)
this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now()); // 起始版本 3.3.0(推荐)
}
@Override
public void updateFill(MetaObject metaObject) {
log.info("start update fill ....");
this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now()); // 起始版本 3.3.0(推荐)
}
}
乐观锁
实现方式:
- 取出记录时,获取当前的version
- 更新时,带上这个version
- 执行更新时,set version = newVersion where version = oldVersion
- 如果version不对,就更新失败
1.先查询获得版本号 version = 1
update user set name = "xxx" , version = version + 1
where id = 2 and version = 1
mybatis_plus乐观锁实现插件
1.添加version字段和注解
@Version //乐观锁注解
private Integer version;
2.配置插件
@Configuration
@EnableTransactionManagement
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
return interceptor;
}
}
多线程下,采用乐观锁保证数据不会被覆盖,而另一个数据可以采用自旋锁保证插入
分页查询
1.导入分页插件
/**
* 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除)
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.H2));
return interceptor;
}
2.查询
Page<Users> page = new Page<>(2,5);//当前页,每页显示条数
usersMapper.selectPage(page,null);//分页参数,查询条件
page.getRecords().forEach(System.out::println);//分页记录
逻辑删除
低版本都需要单独配置Config插件
1.配置
mybatis-plus:
global-config:
db-config:
logic-delete-field: flag # 全局逻辑删除的实体字段名(since 3.3.0,配置后可以忽略不配置步骤2)
logic-delete-value: 1 # 逻辑已删除值(默认为 1)
logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)
2.设置逻辑删除字段
@TableLogic
private Integer deleted;
条件构造器QueryWapper
@Test
void contextLoads() {
//----------查询多个
//查询一个复杂的,比如查询用户name、邮箱不为空,年龄大于20的用户
QueryWrapper<User> wrapper = new QueryWrapper<>(); //首先新建一个 QueryWrapper
//链式编程 添加查询条件
wrapper.isNotNull("name")
.eq("email","2455555659@qq.com")
.ge("age",12);
userMapper.selectList(wrapper).forEach(System.out::println);
//----------查询单个
User user = userMapper.selectOne(wrapper); //出现多个结果会报错,查询一个
System.out.println("user = " + user);
}
// eq相等 ne不相等, gt大于, lt小于 ge大于等于 le 小于等于
// equal/ not equal/ greater than/ less than/ less than or equal/ great than or equal/
@Test
void test2() {
//查询区间内的记录
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.between("age",20,30);
Integer count = userMapper.selectCount(wrapper);
System.out.println("count = " + count);
}
@Test
void test3() {
//模糊查询
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.like("name",99) // 名字中 存在 99
.notLike("name",6) // 名字中 不存在 6
.likeRight("email",2) // 邮箱 最右边是m %m
.likeLeft("email","m"); // 邮箱 最左边是2 2%
userMapper.selectMaps(wrapper);
}
void test4() {
//子查询
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.inSql("id","select id from table where id <2");
userMapper.selectObjs(wrapper).forEach(System.out::println);
}
@Test
void test5() {
//排序
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.orderByAsc("id"); //根据id升序排列 降序orderByDesc()略
userMapper.selectList(wrapper).forEach(System.out::println);
}
@Test
void test7() {
//分组排序
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.groupBy("version").having("version = 1");
userMapper.selectList(wrapper).forEach(System.out::println);
}
代码生成器
// 演示例子,执行 main 方法控制台输入模块表名回车自动生成对应项目目录中
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();
// 1、创建全局配置类的对象
GlobalConfig gc = new GlobalConfig();
//获取当前项目路径
String projectPath = System.getProperty("user.dir");
System.out.println("projectPath = " + projectPath);
//自动生成代码存放的路径
gc.setOutputDir(projectPath + "/src/main/java");
//设置 --作者注释
gc.setAuthor("jdw");
//是否打开文件夹
gc.setOpen(false);
//是否覆盖已有文件
gc.setFileOverride(false);
//各层文件名称方式,例如: %sAction 生成 UserAction %s占位符
gc.setServiceName("%sService");
//设置日期策略 date类型
gc.setDateType(DateType.ONLY_DATE);
//设置主键策略 雪花算法
gc.setIdType(IdType.ASSIGN_ID);
//设置开启 swagger2 模式
gc.setSwagger2(true);
//把全局配置放入代码生成器
mpg.setGlobalConfig(gc);
// 2、数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/vueblog?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=Asia/Shanghai");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("123456");
dsc.setDbType(DbType.MYSQL);
mpg.setDataSource(dsc); //把数据源配置加入到代码生成器
// 3、包配置
PackageConfig pc = new PackageConfig();
pc.setParent("com.jdw");
pc.setEntity("entity");
pc.setMapper("mapper");
pc.setService("service");
pc.setController("controller");
// ... 有默认值,点击查看源码
mpg.setPackageInfo(pc);//包加入代码生成器
// 4、策略配置
StrategyConfig strategy = new StrategyConfig();
//下划线转驼峰命名 表
strategy.setNaming(NamingStrategy.underline_to_camel);
// 下划线转驼峰命名字段
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
//实体类是否加上lombok注解
strategy.setEntityLombokModel(true);
//控制层采用RestControllerStyle注解
strategy.setRestControllerStyle(true);
// RequestMapping中 驼峰转连字符 -
strategy.setControllerMappingHyphenStyle(true);
//要映射的数据库表名 (重点)
strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
//添加表名前缀
//strategy.setTablePrefix("m_"); //自动拼接上m_
//逻辑删除字段名
strategy.setLogicDeleteFieldName("deleted");
//乐观锁字段名
strategy.setVersionFieldName("version");
// -------自动填充策略
ArrayList<TableFill> fillList = new ArrayList<>();
fillList.add(new TableFill("createTime", FieldFill.INSERT));
fillList.add(new TableFill("updateTime",FieldFill.INSERT_UPDATE));
// 参数是 List<TableFill> 的链表
strategy.setTableFillList(fillList);
mpg.setStrategy(strategy);
//---------------------------------
// 自定义配置
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<>();
// 自定义配置会被优先输出
focList.add(new FileOutConfig(templatePath) {
@Override
//输出了 静态资源下的 Mapper
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()
+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// FreemarkerTemplateEngine模板引擎
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
}