相关依赖
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
<version>8.0.18</version>
</dependency>
<!-- mybatis plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
<!-- mybatis plus generator -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.5.1</version>
</dependency>
<!--freemarker模板-->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
</dependency>
生成器
/**
* @author zhangzhenfei
*/
public class UserGenerator {
/**
* 项目根目录
*/
private static final String PROJECT_ROOT_PATH = System.getProperty("user.dir");
public static void main(String[] args) {
// 1、数据源配置
DataSourceConfig.Builder datasourceBuilder = new DataSourceConfig.Builder(
"jdbc:mysql://172.0.0.1:3306/test_user?useUnicode=true&characterEncoding=UTF-8&serverTimezone=CTT&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=CONVERT_TO_NULL",
"root",
"abcde*123BB"
);
// 2、创建代码生成器对象
FastAutoGenerator generator = FastAutoGenerator.create(datasourceBuilder);
// 3、全局配置
generator.globalConfig(builder -> {
// 设置作者
builder.author("zhangzhenfei")
// 定义生成的实体类中日期类型
.dateType(DateType.ONLY_DATE)
// 注释时间策略。
.commentDate("yyyy-MM-dd")
// 生成后是否打开资源管理器:否
.disableOpenDir()
// 开启 swagger 模式。如果开启,需要导入 swagger 的 pom 依赖
.enableSwagger()
// 指定输出目录
.outputDir(PROJECT_ROOT_PATH + "/src/main/java");
});
// 4、包配置
generator.packageConfig(builder -> {
// 父包名. ===========1.手动修改设置===========
builder.parent("com.artron.access.statistical")
// 将要生成的模块名称. ===========2.手动修改设置===========
.moduleName("aas")
// 设置生成的 控制层 文件夹名称
.controller("controller")
// 设置生成的 实体类 文件夹名称
.entity("entity")
// 设置生成的 服务层 文件夹名称
.service("service")
// 设置生成的 映射层 文件夹名称
.mapper("mapper")
// mapper.xml 文件路径。单模块下,其他文件路径默认即可。 ;
.pathInfo(Collections.singletonMap(OutputFile.mapperXml, PROJECT_ROOT_PATH + "/src/main/resources/mapper"));
});
// 5、策略配置
generator.strategyConfig(builder -> {
// 设置数据库表名称. 如果不设置,则会将数据库中所有表都生成。(注意:需要与数据库中表名称一致,前缀也需添加)
// ===========3.手动修改设置。===========
builder.addInclude("tags")
// 过滤表前缀,生成的类名会去掉这个前缀
.addTablePrefix("t_", "p_")
// 第一阶段
// 是否生成 entity:是
.entityBuilder()
// 开启lombok
.enableLombok()
// 设置生成的实体类名称. 默认配置不带 Entity 后缀,我习惯添加上
.convertFileName(entityName -> entityName + "Entity")
// 开启实体时字段注解。 会在生成的实体类的字段上,添加注解: @TableField("nickname")
.enableTableFieldAnnotation()
// 设置主键Id生成策略,设置为默认的雪花算法(ASSIGN_ID)
.idType(IdType.ASSIGN_ID)
// 逻辑删除字段名。(与数据库中字段对应)
.logicDeleteColumnName("is_deleted")
// 逻辑删除属性名。(定义在实体中的属性)。 会在生成的实体类的字段上,添加注解:@TableLogic
.logicDeletePropertyName("isDeleted")
// 会在实体类的该字段上追加注解[@TableField(value = "create_time", fill = FieldFill.INSERT)]
.addTableFills(new Column("created_at", FieldFill.INSERT))
// 会在实体类的该字段上追加注解[@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)]
.addTableFills(new Column("updated_at", FieldFill.INSERT_UPDATE))
// 第二阶段
.mapperBuilder()
// 开启 @Mapper 注解。 会在生成的 mapper 类上,添加注解:@Mapper
.enableMapperAnnotation()
// 启用 BaseResultMap 生成。 会在 mapper.xml文件生成[通用查询映射结果]配置。
.enableBaseResultMap()
// 启用 BaseColumnList。 会在mapper.xml文件生成[通用查询结果列 ]配置
.enableBaseColumnList()
// 第三阶段
.serviceBuilder()
// 设置生成的实体类名称。 默认配置名称前有个I,我习惯添去掉
.convertServiceFileName(serviceName -> serviceName + "Service")
// 第四阶段
.controllerBuilder()
// 开启 @RestController 注解。 会在生成的 Controller 类上,添加注解:@RestController
.enableRestStyle()
// 开启驼峰转连字符
.enableHyphenStyle();
});
// 6. 模板引擎配置,默认为 Velocity , 可选模板引擎 Freemarker 或 Beetl
generator.templateConfig(new Consumer<TemplateConfig.Builder>() {
@Override
public void accept(TemplateConfig.Builder builder) {
// 实体类使用我们自定义模板
builder.entity("templates/myentity.java");
}
}).templateEngine(new FreemarkerTemplateEngine());
generator.execute();
}
}
字段充填
/**
* @Author zhangzhenfei
*/
@Slf4j
@Component
public class MPMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
log.info("start insert fill......");
this.setFieldValByName("createdAt", new Date(), metaObject);
this.setFieldValByName("updatedAt", new Date(), metaObject);
this.setFieldValByName("version", 0, metaObject); //新增就设置版本值为0
}
@Override
public void updateFill(MetaObject metaObject) {
log.info("start update fill......");
this.setFieldValByName("updatedAt", new Date(), metaObject);
}
}
乐观锁、分页
@MapperScan("com.access.statistical.*.mapper")//扫描
@EnableTransactionManagement
@Configuration
public class MPConfig {
/**
* 乐观锁插件-在实体类的字段上加上@Version注解
* @return
*/
@Bean
public MybatisPlusInterceptor mybatisPlusOptimisticLockerInnerInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
return interceptor;
}
/**
* 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除)
*/
@Bean
public MybatisPlusInterceptor mybatisPlusPaginationInnerInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}
生成模板
package ${package.Entity};
<#list table.importPackages as pkg>
import ${pkg};
</#list>
<#if swagger>
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
</#if>
<#if entityLombokModel>
import lombok.Data;
<#if chainModel>
import lombok.experimental.Accessors;
</#if>
</#if>
/**
* <p>
* ${table.comment!}
* </p>
*
* @author ${author}
* @since ${date}
*/
<#if entityLombokModel>
@Data
<#if chainModel>
@Accessors(chain = true)
</#if>
</#if>
<#if table.convert>
@TableName("${schemaName}${table.name}")
</#if>
<#if swagger>
@ApiModel(value = "${entity}对象", description = "${table.comment!}")
</#if>
<#if superEntityClass??>
public class ${entity} extends ${superEntityClass}<#if activeRecord><${entity}></#if> {
<#elseif activeRecord>
public class ${entity} extends Model<${entity}> {
<#elseif entitySerialVersionUID>
public class ${entity} implements Serializable {
<#else>
public class ${entity} {
</#if>
<#if entitySerialVersionUID>
private static final long serialVersionUID = 1L;
</#if>
<#-- ---------- BEGIN 字段循环遍历 ---------->
<#list table.fields as field>
<#if field.keyFlag>
<#assign keyPropertyName="${field.propertyName}"/>
</#if>
<#if field.comment!?length gt 0>
<#if swagger>
@ApiModelProperty("${field.comment}")
<#else>
/**
* ${field.comment}
*/
</#if>
</#if>
<#if field.keyFlag>
<#-- 主键 -->
<#if field.keyIdentityFlag>
@TableId(value = "${field.annotationColumnName}", type = IdType.AUTO)
<#elseif idType??>
@TableId(value = "${field.annotationColumnName}", type = IdType.${idType})
<#elseif field.convert>
@TableId("${field.annotationColumnName}")
</#if>
<#-- 普通字段 -->
<#elseif field.fill??>
<#-- ----- 存在字段填充设置 ----->
<#if field.convert>
@TableField(value = "${field.annotationColumnName}", fill = FieldFill.${field.fill})
<#else>
@TableField(fill = FieldFill.${field.fill})
</#if>
<#elseif field.convert>
@TableField("${field.annotationColumnName}")
</#if>
<#-- 乐观锁注解 -->
<#if field.versionField>
@Version
</#if>
<#-- 逻辑删除注解 -->
<#if field.logicDeleteField>
@TableLogic
</#if>
private ${field.propertyType} ${field.propertyName};
</#list>
<#------------ END 字段循环遍历 ---------->
<#if !entityLombokModel>
<#list table.fields as field>
<#if field.propertyType == "boolean">
<#assign getprefix="is"/>
<#else>
<#assign getprefix="get"/>
</#if>
public ${field.propertyType} ${getprefix}${field.capitalName}() {
return ${field.propertyName};
}
<#if chainModel>
public ${entity} set${field.capitalName}(${field.propertyType} ${field.propertyName}) {
<#else>
public void set${field.capitalName}(${field.propertyType} ${field.propertyName}) {
</#if>
this.${field.propertyName} = ${field.propertyName};
<#if chainModel>
return this;
</#if>
}
</#list>
</#if>
<#if entityColumnConstant>
<#list table.fields as field>
public static final String ${field.name?upper_case} = "${field.name}";
</#list>
</#if>
<#if activeRecord>
@Override
public Serializable pkVal() {
<#if keyPropertyName??>
return this.${keyPropertyName};
<#else>
return null;
</#if>
}
</#if>
<#if !entityLombokModel>
@Override
public String toString() {
return "${entity}{" +
<#list table.fields as field>
<#if field_index==0>
"${field.propertyName}=" + ${field.propertyName} +
<#else>
", ${field.propertyName}=" + ${field.propertyName} +
</#if>
</#list>
"}";
}
</#if>
}
物理删除
配置文件: logic-delete-value: 1 # 逻辑已删除值(默认为 1) logic-not-delete-value: 0 # 逻辑未删除值(默认为 0) 实体: @ApiModelProperty("是否删除") @TableField("is_deleted") @TableLogic private Integer isDeleted; 时间: @ApiModelProperty("创建时间") @TableField(value = "created_at", fill = FieldFill.INSERT) private Date createdAt; @ApiModelProperty("修改时间") @TableField(value = "updated_at", fill = FieldFill.INSERT_UPDATE) private Date updatedAt;
┗( ▔, ▔ )┛┗( ▔, ▔ )┛┗( ▔, ▔ )┛┗( ▔, ▔ )┛┗( ▔, ▔ )┛┗( ▔, ▔ )┛┗( ▔, ▔ )┛┗( ▔, ▔ )┛┗( ▔, ▔ )┛┗( ▔, ▔ )┛