mybatis-Plus教程

原笔记存储于有道笔记中,更适合阅读
文档:mybatis-Plus使用记录.note
链接:http://note.youdao.com/noteshare?id=b916469aa6376514f32309bf88c39a79&sub=05381DE4DF7D43D4A5287C5BDB0464E1

参考博客:
https://blog.csdn.net/CodeInCoke/article/details/121030290

一、介绍
二、快速实践
1、导入对应的依赖
2、链接数据库
3、创建pojo类
4、创建mapper
5、穿插springboot中的测试类用法,直接示范样例类,@test用法
6、插入语法
7、更新语法
8、乐观锁
9、查询语法
10、删除语法
10、条件构造器Wrapper
11、代码自动生成器(暂未实践与学习)
一、介绍
MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window)的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
拥有以下特性:
无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
损耗小:启动即会自动注入基本 CURD,性能基本无损耗,直接面向对象操作,BaseMapper
强大的 CRUD 操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分 CRUD 操作,更有强大的条件构造器,满足各类使用需求,简单的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 操作智能分析阻断,也可自定义拦截规则,预防误操作
二、快速实践
1、导入对应的依赖


mysql
mysql-connector-java



org.projectlombok
lombok



com.baomidou
mybatis-plus-boot-starter
3.3.1


org.springframework.boot
spring-boot-starter-web


org.springframework.boot
spring-boot-starter


org.springframework.boot
spring-boot-autoconfigure


注意:使用mybatis-plus可以节省大量代码,不要同时导入mybatis和mybatis-plus,可能存在版本冲突,最主要的原因是mybatis-plus中内部集成了mybatis,重复引用的话就可能导致互相之间的版本冲突
mybatis-plus与springboot的依赖也会有大量冲突,因为myP中也集成了spring的相关依赖

2、链接数据库
注意:mysql8后的链接数据库驱动变为com.mysql.cj.jdbc.Driver,而且需要加上时区的配置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://10.208.225.119:3326/brmdb?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&failOverReadOnly=false&useSSL=false&serverTimezone=Asia/Beijing
spring.datasource.username=
spring.datasource.password=

开启日志打印sql语句,配置文件中引入以下配置,指向自己的mapper路径即可
logging.level.com.sitech.test.rule.mapper=DEBUG

3、创建pojo类
@Data
@AllArgsConstructor #有参构造器
@NoArgsConstructor #无参构造器
public class User {
//常见的数据库中主键自动设置方法有(uuid、自增id、雪花算法、redis生成、zookeeper生成)
private Long id;
private String name;
private Integer age;
private String email;
}

启动类配置配置,mapper的目标文件夹
@SpringBootApplication
@MapperScan(“com.jdw.mapper”)

4、创建mapper

@Mapper
public interface UserMapper extends BaseMapper {
//所有的crud都编写完成了
}

5、穿插springboot中的测试类用法,直接示范样例类,@test用法
package com.sitech.test.rule;

import com.sitech.test.rule.mapper.SecondCheckLimitMapper;
import com.sitech.test.rule.model.SecondCheckLimit;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;
import java.util.List;

/**

  • @author: renzj
  • @date: 2022-05-06
  • @description:
  • @version: 1.0
    */
    @RunWith(SpringRunner.class)
    @SpringBootTest(classes = {TestApplication.class}, properties = {“application.properties”})

public class TestMybatisPlus {
private static final Logger logger = LogManager.getLogger(com.sitech.test.rule.controller.TestMybatisPlus.class);
@Autowired
private SecondCheckLimitMapper limitMapper;

@Test
public void getAllLimit(){
    List<SecondCheckLimit> secondCheckLimits = limitMapper.selectList(null);
    secondCheckLimits.forEach(logger::info);
}

}

6、插入语法
a、普通插入
//测试插入
@Test
public void testInsert(){
User user = new User();
user.setName(“小蒋”);
user.setAge(3);
user.setEmail(“2474950959@qq.com”);
//没有设置ID却自动生成的ID
int result = userMapper.insert(user);
System.out.println("result = " + result);
System.out.println("user = " + user);
}

b、主键生成策略
雪花算法,默认采用的生成算法
snowflake是Twitter开源的分布式ID生成算法,结果是一个long型的ID。其核心思想是:使用41bit作为毫秒数,10bit作为机器的ID(5个bit是数据中心,5个bit的机器ID),12bit作为毫秒内的流水号(意味着每个节点在每毫秒可以产生 4096 个 ID),最后还有一个符号位,永远是0。具体实现的代码可以参看https://github.com/twitter/snowflake。雪花算法支持的TPS可以达到419万左右(2^22*1000),几乎保证全球唯一。
雪花算法在工程实现上有单机版本和分布式版本。单机版本如下,分布式版本可以参看美团leaf算法:https://github.com/Meituan-Dianping/Leaf
可以在User类的id属性上加入注解TableId更改和查看策略
type = IdType.ASSIGN_ID,全局唯一id,雪花算法

public class User {
@TableId(type = IdType.ASSIGN_ID,value = “id”)//枚举注解,使用ID_WORKER策略,全局唯一ID,数据库设置自增也没用
private Long id;
private String name;
private Integer age;
private String email;
}

主键设置自增的情况下,需要在id上加入下列代码
@TableId(type = IdType.AUTO)
private Long id;

其他策略
public enum IdType {
/**
* 数据库ID自增
*

该类型请确保数据库设置了 ID自增 否则无效


/
AUTO(0),
/
*
* 该类型为未设置主键类型(注解里等于跟随全局,全局里约等于 INPUT)
/
NONE(1),
/
*
* 用户输入ID
*

该类型可以通过自己注册自动填充插件进行填充


*/
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);

private final int key;

IdType(int key) {
    this.key = key;
}

}

7、更新语法
a、普通更新
//更新测试
@Test
public void testUpdateByID() {
User user = new User();
user.setId(7L);
user.setName(“小小”);
user.setAge(18);//这一行后加
int i = userMapper.updateById(user);//受影响的行数,参数是一个user不是id,点击看源码
System.out.println("i = " + i);
}

b、自动填充
创建时间、更新时间!这个操作是自动化完成的,不要手动更新!

gmt_create、gmt_modified几乎在所有表都要配置上,而且自动化填充。gmt是时间时间的意思

方式一、数据库级别(不建议)
在数据库种添加字段gmt_create、gmt_modified,然后在pojo类中添加这两个属性,下次就可以查看了

private Data gmtCreate;
private Data gmtModified;

方式二、代码级别
1、在数据库中删除掉根据当前时间戳更新的选项

2、在实体类的成员变量上添加注解@TableField
//字段添加填充内容
@TableField(fill = FieldFill.INSERT ,value = “create_time”)
private LocalDateTime createTime;
@TableField(fill = FieldFill.INSERT_UPDATE ,value = “update_time”)
private LocalDateTime updateTime;

源码注释
public @interface TableField { //源码

/**
 * 字段自动填充策略
 * <p>
 * 在对应模式下将会忽略 insertStrategy 或 updateStrategy 的配置,等于断言该字段必有值
 */
FieldFill fill() default FieldFill.DEFAULT;

...

}

//填充策略
public enum FieldFill {
/**
* 默认不处理
/
DEFAULT,
/
*
* 插入时填充字段
/
INSERT,
/
*
* 更新时填充字段
/
UPDATE,
/
*
* 插入和更新时填充字段
*/
INSERT_UPDATE
}

3、编写处理器来处理这个注解
@Slf4j //日志
@Component//以组件的形式把这个处理器注册到IOC容器中
public class MyMetaObjectHandler implements MetaObjectHandler {

//插入时启动  第三个参数 LocalDateTime 一定要和 createTime成员变量的值的类型一致,不然是null 如果是date就都设置date
@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(推荐)
}

}

4、接下来的代码执行插入、更新时都会自动设置时间了
8、乐观锁
a、测试更新
1、在数据库添加version字段,int型,默认0,长度10,不自增
2、在User类中添加对应属性:
说明: Version
支持的数据类型只有:int,Integer,long,Long,Date,Timestamp,LocalDateTime
整数类型下 newVersion = oldVersion + 1
newVersion 会回写到 entity 中
仅支持 updateById(id) 与 update(entity, wrapper) 方法
在 update(entity, wrapper) 方法下, wrapper 不能复用!!!
3、在config下注册组件,开启乐观锁拦截器
@EnableTransactionManagement //开启事务
@Configuration //配置类注解
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());//乐观锁插件拦截器OptimisticLockerInnerInterceptor
return mybatisPlusInterceptor;
}
}

4.测试乐观锁
@Test
public void testOptimisticLocker(){
//1、查询用户信息
User user = userMapper.selectById(1L);
//2、修改用户信息
user.setEmail(“123@qq.com”);
user.setName(“小垃圾”);
//3、更新操作
userMapper.updateById(user);
}

测试截图

5.模拟多线程下乐观锁失败案例
@Test
public void testOptimisticLocker2(){
//模拟多线程
User user = userMapper.selectById(3L);
user.setEmail(“123jdw@qq.com”);
user.setName(“帅小伙111”);//我们在这里对线程1修改值

    //线程2插队
    User user2 = userMapper.selectById(3L);
    user2.setEmail("321jdw@qq.com");
    user2.setName("帅小伙222");
    userMapper.updateById(user2); //线程2抢先提交

    userMapper.updateById(user);//线程1失败,乐观锁在这种情况下防止了脏数据存在,没有乐观锁就会有覆盖掉线程2的操作
}

9、查询语法
a、查询单用户
//查询单用户
@Test
public void testSelectBatchId(){
User user = userMapper.selectById(1L);
System.out.println(user);
}

b、多用户查询
@Test
public void testSelectBatchIds() {
//Arrays.asList()创建了一个固定大小的集合
List users = userMapper.selectBatchIds(Arrays.asList(1, 2, 3));//参数Collection的集合
users.forEach(System.out::println);
}

c、条件查询
//条件查询,-- HashMap
@Test
public void testSelectByMap() {
HashMap<String, Object> map = new HashMap<>();
//定义查询条件
map.put(“name”, “小蒋”); //where k = v
map.put(“age”,3);
List users = userMapper.selectByMap(map);
users.forEach(System.out::println);
}

d、模糊查询
QueryWrapper limitQueryWrapper = new QueryWrapper<>();
limitQueryWrapper.like(“push_type”, “family”);
List secondCheckLimits = limitMapper.selectList(limitQueryWrapper);
secondCheckLimits.forEach(logger::info);

进阶用法,判断参数是否为空进行查询
QueryWrapper limitQueryWrapper = new QueryWrapper<>();
limitQueryWrapper.like(“push_type”, “family”);
List secondCheckLimits = limitMapper.selectList(limitQueryWrapper);
secondCheckLimits.forEach(logger::info);

第一个参数:该参数是一个布尔类型,只有该参数是true时,才将like条件拼接到sql中;本例中,如果name字段不为空,则拼接name字段的like查询条件;
第二个参数:该参数是数据库中的字段名;
第三个参数:该参数值字段值;
需要说明的是,这里的like查询是使用的默认方式,也就是说在查询条件的左右两边都有%:NAME = ‘%王%’;
如果只需要在左边或者右边拼接%,可以使用likeLeft或者likeRight方法。
entityWrapper.like(“name”, name, SqlLike.LEFT);

e、分页查询,注意分页的使用,依赖版本需要在3.4.0以上
1、配置拦截器
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());//创建乐观锁拦截器 OptimisticLockerInnerInterceptor
mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); //插件分页拦截器,我的是mysql
return mybatisPlusInterceptor;
}
}

2、使用page对象
//测试分页查询
@Test
public void testPage() {
Page page = new Page<>(1,5); //开启拦截器后,会注册一个page对象 当前页,每页条数
//方法源码: <P extends IPage> P selectPage(P page, @Param(Constants.WRAPPER) Wrapper queryWrapper);
userMapper.selectPage(page,null); //分页查询
page.getRecords().forEach(System.out::println); //获取分页后的数据 打印
System.out.println(page.getTotal()); //获取记录总数
}

3、源码解析
/**源码

  • 分页构造函数
  • @param current 当前页
  • @param size 每页显示条数
    */
    public Page(long current, long size) {
    this(current, size, 0);
    }

4、日志分析

5、携带条件的分页查询则可以添加合适的条件携带器queryWrapper
10、删除语法
a、常规删除,全部删除
//删除测试
@Test
public void testDeleteById(){
userMapper.deleteById(1453324799370616833L);
// userMapper.delete(null); //全部删除
}

b、从上往下分别是:根据id删除,根据 entity 条件删除记录,通过多个id批量删除,根据map条件删除

c、逻辑删除
物理删除:在数据库中移除
逻辑删除:数据库中没有移除,而是在代码中使用一个变量来使他失效!(如:delete = 0 => delete = 1; )
1、在数据库添加deleted字段

2、同步实体类中,同时添加@TableLogic//逻辑删除注解
@TableLogic//逻辑删除
private Integer deleted;

3、在配置文件yml中配置
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)

4、测试删除
执行删除操作,实际上是执行更新操作,把deleted字段改为1了
@Test
public void testDeleteById(){
userMapper.deleteById(1L);
// userMapper.delete(null); //全部删除
}

如果我们再去查询这个id=1的用户发现,查不到,mybatis-plus 自动拼接了deleted字段在where中判断。
@Test
public void testSelectBatchId() {
User user = userMapper.selectById(1L);
System.out.println(user);
}

10、条件构造器Wrapper
条件构造器就相当于sql中加了一个where,QueryWrapper和 UpdateWrapper,分别是用于生成查和改 的 sql 的 where 条件
a、 查询多条记录与单条记录
@Test
void contextLoads() {
//----------查询多个
//查询一个复杂的,比如查询用户name、邮箱不为空,年龄大于20的用户
QueryWrapper 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/

日志分析,就是在where中添加了多个条件

b、区间查询与计数,between(),selectCount()
@Test
void test2() {
//查询区间内的记录
QueryWrapper wrapper = new QueryWrapper<>();
wrapper.between(“age”,20,30);
Integer count = userMapper.selectCount(wrapper);
System.out.println("count = " + count);
}

c、模糊查询
@Test
void test3() {
//模糊查询
QueryWrapper 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);
}

d、多表查询
void test4() {
//子查询
QueryWrapper wrapper = new QueryWrapper<>();
wrapper.inSql(“id”,“select id from table where id <2”);
userMapper.selectObjs(wrapper).forEach(System.out::println);
}

e、排序
@Test
void test5() {
//排序
QueryWrapper wrapper = new QueryWrapper<>();
wrapper.orderByAsc(“id”); //根据id升序排列 降序orderByDesc()略
userMapper.selectList(wrapper).forEach(System.out::println);
}

f、分组,条件
@Test
void test7() {
//分组排序
QueryWrapper wrapper = new QueryWrapper<>();
wrapper.groupBy(“version”).having(“version = 1”);
userMapper.selectList(wrapper).forEach(System.out::println);
}

11、代码自动生成器(暂未实践与学习)
AutoGenerator 是 MyBatis-Plus 的代码生成器,通过 AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各个模块的代码,极大的提升了开发效率。
1、添加如下依赖


com.baomidou
mybatis-plus-generator
3.4.1



io.swagger
swagger-annotations
1.5.20



org.springframework.boot
spring-boot-starter-freemarker

在任意文件夹新建立一个类进行配置
类的代码如下
package com.jdw;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
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.DateType;
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;

// 演示例子,执行 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();
}

}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值