新版本(针对3.5.1版本)
依赖导入
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
自动填充功能
必要条件:数据库中有create_time,update_time字段(或者类似的也行),不需要默认值和更新
实体类的字段属性上需要增加注解
@TableField(fill = FieldFill.INSERT)
private Date createTime;
@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;
注解源码解释
public enum FieldFill {
DEFAULT,
INSERT,
UPDATE,
INSERT_UPDATE
}
创建一个handler包下
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
log.info("start insert fill");
this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
this.strictInsertFill(metaObject, "updateTime", Date.class, new Date());
}
@Override
public void updateFill(MetaObject metaObject) {
log.info("start update fill");
this.strictInsertFill(metaObject, "updateTime", Date.class, new Date());
}
}
乐观锁插件
必要条件:数据库中需要有version字段,设定其默认值为1
@Configuration
@MapperScan("com.lzj.mapper")
public class MyBatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
return mybatisPlusInterceptor;
}
}
分页插件配置
@Configuration
@MapperScan("com.lzj.mapper")
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.H2));
return interceptor;
}
}
自定义代码生成(适用于3.5.1及以上版本)
快速生成自定义代码
需要导入的3个依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
拿去即用,修改下以下数据即可:
- 数据库表名
- 数据源信息
- 作者名字
- 父包名
- 逻辑删除(需要使用可以取消注释)
- 过滤表前缀
- 模板引擎
package com.lzj;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
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.Collections;
import java.util.List;
public class CodeGenerator {
public static void main(String[] args) {
List<String> tables = new ArrayList<>();
tables.add("m_user");
tables.add("m_blog");
FastAutoGenerator.create("jdbc:mysql://localhost:3306/vueblog?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai","root","root")
.globalConfig(builder -> {
builder.author("lzj")
.outputDir(System.getProperty("user.dir")+"/src/main/java")
.enableSwagger()
.commentDate("yyyy-MM-dd hh:mm:ss")
.dateType(DateType.ONLY_DATE)
.fileOverride()
.disableOpenDir();
})
.packageConfig(builder -> {
builder.parent("com.lzj")
.entity("entity")
.service("service")
.serviceImpl("serviceImpl")
.controller("controller")
.mapper("mapper")
.xml("mapper")
.other("utils")
.pathInfo(Collections.singletonMap(OutputFile.xml,System.getProperty("user.dir")+"/src/main/resources/mapper"));
})
.strategyConfig(builder -> {
builder.addInclude(tables)
.addTablePrefix("m_")
.serviceBuilder()
.formatServiceFileName("%sService")
.formatServiceImplFileName("%sServiceImpl")
.entityBuilder()
.enableLombok()
.logicDeleteColumnName("deleted")
.naming(NamingStrategy.underline_to_camel)
.columnNaming(NamingStrategy.underline_to_camel)
.enableTableFieldAnnotation()
.controllerBuilder()
.formatFileName("%sController")
.enableRestStyle()
.mapperBuilder()
.enableBaseResultMap()
.superClass(BaseMapper.class)
.formatMapperFileName("%sMapper")
.enableMapperAnnotation()
.formatXmlFileName("%sMapper");
})
.templateEngine(new FreemarkerTemplateEngine())
.execute();
}
}
交互生成自定义代码格式
这种方式我只提供格式,可以将快速生成的修改成下面的格式即可使用
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("=====================数据库配置=======================");
System.out.println("请输入 URL");
String url = scan.next();
System.out.println("请输入 username");
String username = scan.next();
System.out.println("请输入 password");
String password = scan.next();
FastAutoGenerator.create(url, username, password)
.globalConfig((scanner, builder) -> builder.author(scanner.apply("=====================全局配置=======================\n请输入作者名称?"))
.outputDir(System.getProperty("user.dir") + "/src/main/java")
.commentDate("yyyy-MM-dd hh:mm:ss")
.dateType(DateType.TIME_PACK)
.enableSwagger()
.fileOverride()
.enableSwagger()
.disableOpenDir()
)
.packageConfig((scanner, builder) -> builder.parent(scanner.apply("=====================包配置=======================\n请输入包名?"))
.moduleName(scanner.apply("请输入父包模块名?"))
.entity("entity")
.service("service")
.serviceImpl("serviceImpl")
.mapper("mapper")
.xml("mapper")
.other("utils")
.pathInfo(Collections.singletonMap(OutputFile.mapperXml, System.getProperty("user.dir")+"/src/main/resources/mapper"))
)
.strategyConfig((scanner, builder) -> {
builder.addInclude(getTables(scanner.apply("=====================策略配置=======================\n请输入表名,多个英文逗号分隔?所有输入 all")))
.serviceBuilder()
.formatServiceFileName("%sService")
.formatServiceImplFileName("%sServiceImpl")
.entityBuilder()
.enableLombok()
.disableSerialVersionUID()
.logicDeleteColumnName("deleted")
.naming(NamingStrategy.underline_to_camel)
.columnNaming(NamingStrategy.underline_to_camel)
.addTableFills(new Column("create_time", FieldFill.INSERT), new Column("modify_time", FieldFill.INSERT_UPDATE))
.enableTableFieldAnnotation()
.controllerBuilder()
.formatFileName("%sController")
.enableRestStyle()
.mapperBuilder()
.superClass(BaseMapper.class)
.formatMapperFileName("%sMapper")
.enableMapperAnnotation()
.formatXmlFileName("%sMapper");
})
.execute();
}
protected static List<String> getTables(String tables) {
return "all".equals(tables) ? Collections.emptyList() : Arrays.asList(tables.split(","));
}
旧版本
旧版本的代码自动生成我还没有使用,所以这里就不写代码自动生成了
乐观锁插件
@MapperScan("com.lzj.mapper")
@EnableTransactionManagement
@Configuration
public class MyBatisPlusConfig {
@Bean
public OptimisticLockerInterceptor optimisticLockerInterceptor(){
return new OptimisticLockerInterceptor();
}
}
分页插件
@Configuration
@MapperScan("com.lzj.mapper")
public class PageConfi {
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
return paginationInterceptor;
}
}
|