package com.duanluan.util;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.builder.ConfigBuilder;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import com.duanluan.common.BaseController;
import org.apache.commons.lang3.StringUtils;
import java.util.Map;
import java.util.Scanner;
import java.util.function.BiConsumer;
/** * 代码生成器:https://github.com/baomidou/generator/blob/develop/mybatis-plus-generator/src/main/java/com/baomidou/mybatisplus/generator/SimpleAutoGenerator.java * * @author duanluan */
public class CodeGenerator {
/** * 读取控制台输入内容 */
private static final Scanner scanner = new Scanner(System.in);
/** * 控制台输入内容读取并打印提示信息 * * @param message 提示信息 * @return */
public static String scannerNext(String message) {
System.out.println(message);
String nextLine = scanner.nextLine();
if (StringUtils.isBlank(nextLine)) {
// 如果输入空行继续等待
return scanner.next();
}
return nextLine;
}
protected static <T> T configBuilder(IConfigBuilder<T> configBuilder) {
return null == configBuilder ? null : configBuilder.build();
}
public static void main(String[] args) {
// 代码生成器
new AutoGenerator(configBuilder(new DataSourceConfig.Builder("jdbc:mariadb://localhost:3307/test", "root", "123456")))
// 全局配置
.global(configBuilder(new GlobalConfig.Builder()
// 覆盖已生成文件,默认 false
.fileOverride()
// 是否打开生成目录,默认 true
.openDir(false)
// 输出目录,默认 windows: D:// linux or mac: /tmp
.outputDir(System.getProperty("user.dir") + "/generator/src/main/java")
// 作者,默认无
.author("duanluan")
// 注释时间(@since),默认 yyyy-MM-dd
.commentDate("")
))
// 包配置
.packageInfo(configBuilder(new PackageConfig.Builder()
// 模块名
.moduleName("")
// 父包名
.parent("com.duanluan")
))
// 自定义配置
.injection(configBuilder(new InjectionConfig.Builder()
.beforeOutputFile(new BiConsumer<TableInfo, Map<String, Object>>() {
@Override
public void accept(TableInfo tableInfo, Map<String, Object> stringObjectMap) {
// 自定义 Mapper XML 生成目录
ConfigBuilder config = (ConfigBuilder)stringObjectMap.get("config");
Map<String, String> pathInfoMap = config.getPathInfo();
pathInfoMap.put("xml_path", pathInfoMap.get("xml_path").replaceAll("/java.*","/resources/mapper"));
stringObjectMap.put("config", config);
}
})
))
// 策略配置
.strategy(configBuilder(new StrategyConfig.Builder()
// 表名
.addInclude(scannerNext("请输入表名(英文逗号分隔):").split(","))
// Entity 策略配置
.entityBuilder()
// 开启 Lombok 模式
.enableLombok()
// 开启生成 serialVersionUID
.enableSerialVersionUID()
// 数据库表映射到实体的命名策略:下划线转驼峰
.naming(NamingStrategy.underline_to_camel)
// 主键策略为自增,默认 IdType.AUTO
.idType(IdType.ASSIGN_ID)
// Controller 策略配置
.controllerBuilder()
// 生成 @RestController 注解
.enableRestStyle()
// 父类
.superClass(BaseController.class)
))
// 模板配置
.template(configBuilder(new TemplateConfig.Builder()
// 自定义模板:https://github.com/baomidou/generator/tree/develop/mybatis-plus-generator/src/main/resources/templates
.entity("/templates/generator/entity.java")
.mapper("/templates/generator/mapper.java")
.service("/templates/generator/service.java", "/templates/generator/serviceImpl.java")
.controller("/templates/generator/controller.java")
))
// 执行并指定模板引擎
.execute(new FreemarkerTemplateEngine());
}
}
package ${package.Entity};
<#list table.importPackages as pkg>
import ${pkg};
</#list>
<#if swagger2??>
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
</#if>
<#if entityLombokModel>
import lombok.Data;
import lombok.EqualsAndHashCode;
<#if chainModel>
import lombok.experimental.Accessors;
</#if>
</#if>
/**
* ${table.comment!}
*
* @author ${author}
<#if date != "">
* @since ${date}
</#if>
*/
<#if entityLombokModel>
@Data
<#if superEntityClass??>
@EqualsAndHashCode(callSuper = true)
<#else>
@EqualsAndHashCode(callSuper = false)
</#if>
<#if chainModel>
@Accessors(chain = true)
</#if>
</#if>
<#if table.convert>
@TableName("${table.name}")
</#if>
<#if swagger2??>
@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}> {
<#else>
public class ${entity} implements Serializable {
</#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 swagger2??>
@ApiModelProperty(value = "${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 字段循环遍历 ---------->
<#-- Lombok 模式 -->
<#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
protected 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>
}
package ${package.Mapper};
import ${package.Entity}.${entity};
import ${superMapperClassPackage};
/**
* ${table.comment!} Mapper
*
* @author ${author}
<#if date != "">
* @since ${date}
</#if>
*/
<#if kotlin>
interface ${table.mapperName} : ${superMapperClass}<${entity}>
<#else>
public interface ${table.mapperName} extends ${superMapperClass}<${entity}> {
}
</#if>
package ${package.Service};
import ${package.Entity}.${entity};
import ${superServiceClassPackage};
/**
* ${table.comment!} 服务
*
* @author ${author}
<#if date != "">
* @since ${date}
</#if>
*/
<#if kotlin>
interface ${table.serviceName} : ${superServiceClass}<${entity}>
<#else>
public interface ${table.serviceName} extends ${superServiceClass}<${entity}> {
}
</#if>
package ${package.ServiceImpl};
import ${package.Entity}.${entity};
import ${package.Mapper}.${table.mapperName};
import ${package.Service}.${table.serviceName};
import ${superServiceImplClassPackage};
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
/**
* ${table.comment!} 服务实现
*
* @author ${author}
<#if date != "">
* @since ${date}
</#if>
*/
@Service
<#if kotlin>
open class ${table.serviceImplName} : ${superServiceImplClass}<${table.mapperName}, ${entity}>(), ${table.serviceName} {
}
<#else>
public class ${table.serviceImplName} extends ${superServiceImplClass}<${table.mapperName}, ${entity}> implements ${table.serviceName} {
@Autowired
private ${table.mapperName} ${table.mapperName?substring(0, 1)?lower_case}${table.mapperName?substring(1)};
}
</#if>
package ${package.Controller};
<#if superControllerClassPackage??>
import ${superControllerClassPackage};
</#if>
import ${package.Service}.${table.serviceName};
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
<#if restControllerStyle>
import org.springframework.web.bind.annotation.RestController;
<#else>
import org.springframework.stereotype.Controller;
</#if>
/**
* ${table.comment!} 前端控制器
*
* @author ${author}
<#if date != "">
* @since ${date}
</#if>
*/
<#if restControllerStyle>
@RestController
<#else>
@Controller
</#if>
@RequestMapping("<#if package.ModuleName?? && package.ModuleName != "">/${package.ModuleName}</#if>/<#if controllerMappingHyphenStyle??>${controllerMappingHyphen}<#else>${table.entityPath}</#if>")
<#if kotlin>
class ${table.controllerName}<#if superControllerClass??> : ${superControllerClass}()</#if>
<#else>
<#if superControllerClass??>
public class ${table.controllerName} extends ${superControllerClass} {
<#else>
public class ${table.controllerName} {
</#if>
@Autowired
private ${table.serviceName} ${table.serviceName?substring(1, 2)?lower_case}${table.serviceName?substring(2)};
}
</#if>
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/duanluan/article/details/118776180
内容来源于网络,如有侵权,请联系作者删除!