一、快速入门
1.1 简介
MyBatis-Plus (简称 MP)是一个 MyBatis (opens new window)的增强工具,在 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 操作智能分析阻断,也可自定义拦截规则,预防误操作
1.2框架结构
1.3 快速入门
- 创建数据表
CREATE DATABASE mybatisPlus;
USE mybatisPlus;
DROP TABLE IF EXISTS user;
CREATE TABLE user
(
id BIGINT(20) NOT NULL COMMENT '主键ID',
name VARCHAR(30) NULL DEFAULT NULL COMMENT '姓名',
age INT(11) NULL DEFAULT NULL COMMENT '年龄',
email VARCHAR(50) NULL DEFAULT NULL COMMENT '邮箱',
PRIMARY KEY (id)
);
INSERT INTO user (id, name, age, email) VALUES
(1, 'Jone', 18, 'test1@baomidou.com'),
(2, 'Jack', 20, 'test2@baomidou.com'),
(3, 'Tom', 28, 'test3@baomidou.com'),
(4, 'Sandy', 21, 'test4@baomidou.com'),
(5, 'Billie', 24, 'test5@baomidou.com');
- 初始化工程
创建一个空的 Spring Boot 工程
- 导入依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.5</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.15</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
- 配置
在 application.properties
配置文件中添加 数据库的相关配置:
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.url=jdbc:mysql://localhost:3306/mybatisPlus?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
在 Spring Boot 启动类中添加 @MapperScan
注解,扫描 Mapper 文件夹:
@SpringBootApplication
@MapperScan("com.mybatisPlus.mapper")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
- 编码
编写实体类 User.java
(此处使用了 Lombok (opens new window)简化代码)
@Data
public class User {
private Long id;
private String name;
private int age;
private String email;
}
编写Mapper类 UserMapper.java
@Mapper
public interface UserMapper extends BaseMapper<User> {
}
- 测试
@Test
public void testSelect() {
System.out.println(("----- selectAll method test ------"));
List<User> userList = userMapper.selectList(null);
Assert.assertEquals(5, userList.size());
userList.forEach(System.out::println);
}
- 结果
二、CURD
2.1 配置日志
#日志配置
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
日志输出
2.2 插入操作
2.2.1 插入测试
- 插入用户
@Test
public void insertTest(){
User user = new User();
user.setName("user");
user.setAge(12);
user.setEmail("2333@163.com");
int insert=userMapper.insert(user);
System.out.println("insert = "+insert);
System.out.println(user);
}
- 插入结果
使用 雪花算法 自动生成Id。
雪花算法
snowflake是Twitter开源的分布式ID生成算法,结果是一个long型的ID。其核心思想是:使用41bit作为毫秒数,10bit作为机器的ID(5个bit是数据中心,5个bit的机器ID),12bit作为毫秒内的流水号(意味着每个节点在每毫秒可以产生 4096 个 ID),最后还有一个符号位,永远是0。具体实现的代码可以参看https://github.com/twitter/snowflake。
2.2.2 主键生成策略
public enum IdType {
AUTO, //数据库自增
NONE, //不设置主键
INPUT, //手动输入主键
ID_WORKER, //默认全局唯一id
UUID, //全局唯一id uuid
ID_WORKER_STR;//ID_WORKER的字符串表示
private int key;
private IdType(int key) { /* compiled code */ }
public int getKey() { /* compiled code */ }
}
默认主键策略
//默认ID_WORKER 全局唯一标识符
@TableId(type = IdType.ID_WORKER)
private Long id;
主键自增
- 实体类字段增加注释
@TableId(type = IdType.AUTO)
private Long id;
- 数据库字段设置为自增
2.3 更新操作
2.3.1 自动填充
原理:
- 实现元对象处理器接口:com.baomidou.mybatisplus.core.handlers.MetaObjectHandler
- 注解填充字段
@TableField(.. fill = FieldFill.INSERT)
生成器策略部分也可以配置!
- 数据库增加字段
create_time
和update_time
- 实体类增加属性
public class User {
...
//字段添加填充内容
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill=FieldFill.INSERT_UPDATE)
private Date updateTime;
}
-
实现元对象处理器接口
注释
@Component
注册为组件
@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.setFieldValByName("updateTime",new Date(),metaObject);
}
@Override
public void updateFill(MetaObject metaObject) {
log.info("start update fill");
this.setFieldValByName("updateTime",new Date(),metaObject);
}
}
-
启动类扫描
扫描配置类
MyMetaObjectHandler
@SpringBootApplication
@MapperScan("com.mybatisPlus.mapper")
@ComponentScan("com.mybatisPlus.handler")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
2.3.2 更新测试
- 测试更新
@Test
public void updateTest(){
User user = new User();
user.setId(1L);
user.setName("Billie");
user.setAge(25);
int update = userMapper.updateById(user);
}
- 测试结果
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-4RCYGzyW-1610295243976)(C:\Users\zhoubao\AppData\Roaming\Typora\typora-user-images\image-20210107204955804.png)]
2.4 乐观锁
当要更新一条记录的时候,希望这条记录没有被别人更新
乐观锁实现方式:
- 取出记录时,获取当前version
- 更新时,带上这个version
- 执行更新时, set version = newVersion where version = oldVersion
- 如果version不对,就更新失败
2.4.1 实现乐观锁
- 数据表增加
version
字段
ALTER TABLE `mybatisplus`.`user`
ADD COLUMN `version` INT NULL DEFAULT 1 AFTER `update_time`;
- 实体类增加属性
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
...
@Version
private Integer version;
...
}
- 配置拦截器
MybatisPlusConfig.java
@EnableTransactionManagement
@Configuration
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
return interceptor;
}
}
-
启动类扫描
扫描配置类MybatisPlusConfig
@SpringBootApplication
@MapperScan("com.mybatisPlus.mapper")
@ComponentScan("com.mybatisPlus.handler")
@ComponentScan("com.mybatisPlus.config")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
2.4.2 测试乐观锁
- 测试代码
@Test
public void optimisticLockerTest(){
User user = userMapper.selectById(1L);
user.setName("user0");
userMapper.updateById(user);
}
-
测试结果
version
自动加1
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-IJotL0lt-1610295243978)(C:\Users\zhoubao\AppData\Roaming\Typora\typora-user-images\image-20210110142252818.png)]
2.5 查询操作
2.5.1 普通查询
- 根据
id
查询selectById
@Test
public void selectByIdTest(){
User user = userMapper.selectById(1L);
System.out.println(user);
}
- 批量查询
selectBatchIds
@Test
public void selectBatchIdsTest(){
List<User> users = userMapper.selectBatchIds(Arrays.asList(1L,2L,3L));
users.forEach(System.out::println);
}
- Map集合查询
selectByMap
@Test
public void selectByMapTest(){
Map<String,Object> map=new HashMap<>();
map.put("name","jack");
List<User> users = userMapper.selectByMap(map);
users.forEach(System.out::println);
}
2.5.2 分页查询
- 配置拦截器
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
//乐观锁配置
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
//分页配置
interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
return interceptor;
}
- 分页测试
@Test
public void selectByPage(){
Page<User> page=new Page<>(0,3);
userMapper.selectPage(page, null);
page.getRecords().forEach(System.out::println);
System.out.println(page.getTotal());
}
2.6 删除操作
2.6.1 普通删除
- 根据
id
删除deleteById
@Test
public void deleteByIdTest(){
int deleted = userMapper.deleteById(1L);
System.out.println(deleted);
}
- 批量删除
deleteBatchIds
@Test
public void deleteBatchIdsTest(){
int deleted = userMapper.deleteBatchIds(Arrays.asList(2L,3L));
System.out.println(deleted);
}
- Map集合删除
deleteByMap
@Test
public void deleteByMapTest(){
Map<String,Object> map=new HashMap<>();
map.put("name","jack");
int deleted = userMapper.deleteByMap(map);
System.out.println(deleted);
}
2.6.2 逻辑删除
- 数据表增加
deleted
字段
ALTER TABLE `mybatisplus`.`user`
ADD COLUMN `deleted` INT(1) NULL DEFAULT 0 AFTER `update_time`;
- 实体类增加属性
deleted
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
...
@TableLogic
private int deleted;
}
- 配置逻辑删除
application.properties
#配置逻辑删除
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0
4.测试逻辑删除
@Test
public void logicDeleteTest(){
userMapper.deleteById(4L);
}
- 逻辑删除结果
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-vVV6x5N7-1610295243982)(C:\Users\zhoubao\AppData\Roaming\Typora\typora-user-images\image-20210110150433767.png)]
三、执行 SQL 分析打印
该功能依赖 p6spy
组件,完美的输出打印 SQL 及执行时长。
p6Spy通过劫持JDBC驱动,在调用实际JDBC
驱动前拦截调用的目标语,达到SQL
语句日志记录的目的。它包括P6Log
和P6Outage
两个模块。
P6Log 用来拦截和记录任务应用程序的 JDBC 语句;P6Outage 专门用来检测和记录超过配置条件里时间的 SQL 语句。
1.导入依赖
<!-- 控制台 SQL日志打印插件 -->
<dependency>
<groupId>p6spy</groupId>
<artifactId>p6spy</artifactId>
<version>3.8.1</version>
</dependency>
2.修改数据库连接`application.properties`
#数据库连接配置
spring.datasource.username=root
spring.datasource.password=root
#spring.datasource.url=jdbc:mysql://localhost:3306/mybatisPlus?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
#spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:p6spy:mysql://localhost:3306/mybatisPlus?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
spring.datasource.driver-class-name=com.p6spy.engine.spy.P6SpyDriver
#日志配置
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
#配置逻辑删除
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0
3.p6spy配置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
- 实现
MessageFormattingStrategy
接口,编写sql输出格式化
import com.p6spy.engine.spy.appender.MessageFormattingStrategy;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class P6spySqlFormatConfig implements MessageFormattingStrategy {
//sql格式化输出
@Override
public String formatMessage(int connectionId, String now, long elapsed, String category, String prepared, String sql, String url) {
return !"".equals(sql.trim())
?
"[ " + LocalDateTime.now() + " ] --- | took " + elapsed + "ms | " + prepared + "|" + category + " | connection " + connectionId + "\n "
+ sql + ";"
: "";
}
//日期格式化
public String formatFullTime(LocalDateTime localDateTime, String pattern) {
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern);
return localDateTime.format(dateTimeFormatter);
}
}
- 测试
@Test
public void testSelect() {
System.out.println(("----- selectAll method test ------"));
List<User> userList = userMapper.selectList(null);
userList.forEach(System.out::println);
}
- 结果分析
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ufU6bJFW-1610295243986)(C:\Users\zhoubao\AppData\Roaming\Typora\typora-user-images\image-20210111001203317.png)]
四、条件查询其Wrapper
- ge & isNotNull
ge:大于等于 >=
例:
ge("age", 18)
—>age >= 18
isNotNull:字段 IS NOT NULL
例:
isNotNull("name")
—>name is not null
测试代码
@Test
public void test() {
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper
.isNotNull("name")
.isNotNull("email")
.ge("age", 12);
userMapper.selectList(wrapper).forEach(System.out::println);
}
执行SQL
SELECT id,name,age,email,version,create_time,update_time,deleted FROM user WHERE deleted=0 AND (name IS NOT NULL AND email IS NOT NULL AND age >= ?)
- eq
eq:等于 =
例:
eq("name", "老王")
—>name = '老王'
测试代码
@Test
public void test() {
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.eq("name","sandy");
List<User> users = userMapper.selectList(wrapper);
users.forEach(System.out::println);
}
执行SQL
SELECT id,name,age,email,version,create_time,update_time,deleted FROM user WHERE deleted=0 AND (name = ?)
- between
between:BETWEEN 值1 AND 值2
例:
between("age", 18, 30)
—>age between 18 and 30
测试代码
@Test
public void test(){
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.between("age",20,24); // 区间
Integer count = userMapper.selectCount(wrapper);// 查询结果数
System.out.println(count);
}
执行SQL
SELECT COUNT( 1 ) FROM user WHERE deleted=0 AND (age BETWEEN ? AND ?)
- notLike
notLike:NOT LIKE ‘%值%’
例:
notLike("name", "王")
—>name not like '%王%'
likeRight:LIKE ‘值%’
例:
likeRight("name", "王")
—>name like '王%'
测试代码
@Test
public void test(){
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper
.notLike("name","e")
.likeRight("email","t");
List<Map<String, Object>> maps = userMapper.selectMaps(wrapper);
maps.forEach(System.out::println);
}
执行SQL
SELECT id,name,age,email,version,create_time,update_time,deleted FROM user WHERE deleted=0 AND (name NOT LIKE ? AND email LIKE ?)
- inSql
inSql:字段 IN ( sql语句 )
例:
inSql("age", "1,2,3,4,5,6")
—>age in (1,2,3,4,5,6)
例:
inSql("id", "select id from table where id < 3")
—>id in (select id from table where id < 3)
测试代码
@Test
public void test(){
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.inSql("id","select id from user where id<5");
List<Object> objects = userMapper.selectObjs(wrapper);
objects.forEach(System.out::println);
}
执行SQL
SELECT id,name,age,email,version,create_time,update_time,deleted FROM user WHERE deleted=0 AND (id IN (select id from user where id<5))
- orderByAsc & orderByDesc
orderByAsc :升序排列:ORDER BY 字段, … ASC
例:
orderByAsc("id", "name")
—>order by id ASC,name ASC
orderByDesc:降序排序:ORDER BY 字段, … DESC
例:
orderByDesc("id", "name")
—>order by id DESC,name DESC
测试代码
@Test
public void test(){
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.orderByAsc("id");
List<User> users = userMapper.selectList(wrapper);
users.forEach(System.out::println);
}
执行SQL
SELECT id,name,age,email,version,create_time,update_time,deleted FROM user WHERE deleted=0 ORDER BY id ASC
五、代码自动生成器
1.创建数据表
DROP TABLE IF EXISTS blog;
CREATE TABLE blog
(
id BIGINT(20) NOT NULL COMMENT '博客主键ID',
name VARCHAR(30) NULL DEFAULT NULL COMMENT '博客名字',
content VARCHAR(50) NULL DEFAULT NULL COMMENT '博客内容',
version INT(11) NULL DEFAULT NULL COMMENT '乐观锁',
create_time DATETIME NULL DEFAULT NULL COMMENT '创建时间',
update_time DATETIME NULL DEFAULT NULL COMMENT '修改时间',
deleted INT(1) NULL DEFAULT 0 COMMENT '逻辑删除',
PRIMARY KEY (id)
);
- 导入依赖
<!--添加 代码生成器 依赖-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.4.1</version>
</dependency>
<!--添加 模板引擎 依赖-->
<!--MyBatis-Plus 支持 Velocity(默认)、Freemarker、Beetl,用户可以选择自己熟悉的模板引擎.-->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.30</version>
</dependency>
-
代码生成器
CodeGenerator.java
通过
strategy.setInclude("tableName")
设置要映射的表名
package com.mybatisPlus.demo;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
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;
public class CodeGenerator {
public static void main(String[] args) {
// 需要构建一个 代码自动生成器 对象
AutoGenerator mpg = new AutoGenerator();
// 配置策略
// 1、全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath+"/src/main/java");
gc.setAuthor("baoZhou");
gc.setOpen(false);
gc.setFileOverride(false); // 是否覆盖
gc.setServiceName("%sService"); // 去Service的I前缀
gc.setIdType(IdType.ID_WORKER);
gc.setDateType(DateType.ONLY_DATE);
mpg.setGlobalConfig(gc);
//2、设置数据源
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/mybatisPlus?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("root");
dsc.setDbType(DbType.MYSQL);
mpg.setDataSource(dsc);
//3、包的配置
PackageConfig pc = new PackageConfig();
pc.setModuleName("blog");
pc.setParent("com.mybatisPlus");
pc.setEntity("entity");
pc.setMapper("mapper");
pc.setService("service");
pc.setController("controller");
mpg.setPackageInfo(pc);
//4、策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setInclude("blog"); // 设置要映射的表名
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setEntityLombokModel(true); // 自动lombok;
strategy.setLogicDeleteFieldName("deleted");//设置逻辑删除
// 5、自动填充配置
TableFill create_time = new TableFill("create_time", FieldFill.INSERT);
TableFill update_time = new TableFill("update_time", FieldFill.INSERT_UPDATE);
ArrayList<TableFill> tableFills = new ArrayList<>();
tableFills.add(create_time);
tableFills.add(update_time);
strategy.setTableFillList(tableFills);
// 乐观锁
strategy.setVersionFieldName("version");
strategy.setRestControllerStyle(true);
strategy.setControllerMappingHyphenStyle(true);
mpg.setStrategy(strategy);
// set freemarker engine
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute(); //执行
}
}
- 生成结果
y.setLogicDeleteFieldName(“deleted”);//设置逻辑删除
// 5、自动填充配置
TableFill create_time = new TableFill(“create_time”, FieldFill.INSERT);
TableFill update_time = new TableFill(“update_time”, FieldFill.INSERT_UPDATE);
ArrayList tableFills = new ArrayList<>();
tableFills.add(create_time);
tableFills.add(update_time);
strategy.setTableFillList(tableFills);
// 乐观锁
strategy.setVersionFieldName(“version”);
strategy.setRestControllerStyle(true);
strategy.setControllerMappingHyphenStyle(true);
mpg.setStrategy(strategy);
// set freemarker engine
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute(); //执行
}
}
4. 生成结果
<img src="C:\Users\zhoubao\AppData\Roaming\Typora\typora-user-images\image-20210110232703621.png" alt="image-20210110232703621" style="zoom:80%;" />