阅读完需:约 9 分钟
AutoGenerator 是 MyBatis-Plus 的代码生成器,通过 AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各个模块的代码,极大的提升了开发效率。
Mybatis-Plus官网:
https://baomidou.com/guide/generator.html#%E4%BD%BF%E7%94%A8%E6%95%99%E7%A8%8B
官网简化版:
public class CodeGeneration {
public static void main(String[] args){
AutoGenerator mpg = new AutoGenerator();
//全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/src/main/java/com/hitotek/htvfactor");
gc.setFileOverride(true);
gc.setActiveRecord(true);//不需要ActiveRecord特性的请改为false
gc.setEnableCache(false);//XML二级缓存
gc.setBaseResultMap(true);//XML ResultMap
gc.setBaseColumnList(false);//XML columList
gc.setAuthor("xjh");//作者
//自定义文件命名,注意%s 会自动填充表实体属性
gc.setControllerName("%sController");
gc.setServiceName("%sService");
gc.setServiceImplName("%sServiceImpl");
gc.setMapperName("%sMapper");
gc.setXmlName("%sMapper");
mpg.setGlobalConfig(gc);
//数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setDbType(DbType.SQL_SERVER);
dsc.setDriverName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
dsc.setUsername("root");
dsc.setPassword("root");
dsc.setUrl("jdbc:sqlserver://127.0.0.1:14332;databaseName=LT_share");
mpg.setDataSource(dsc);
//策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setEntityLombokModel(true); // 设置Lombok的使用
strategy.setRestControllerStyle(true); // 生成RestController控制器
strategy.setControllerMappingHyphenStyle(true); // url驼峰连接字符
strategy.setEntityTableFieldAnnotationEnable(true); // 是否生成实体时,生成字段注解
strategy.setTableFillList(Arrays.asList(new TableFill("create_time", FieldFill.INSERT),
new TableFill("update_time", FieldFill.INSERT_UPDATE)));
strategy.setTablePrefix(new String[]{});//此处可以修改您的表前缀
strategy.setNaming(NamingStrategy.underline_to_camel);//表名生成策略
strategy.setInclude(new String[]{"DataAcquisition_DataShare"});//需要生成的表
strategy.setSuperServiceClass(null);
strategy.setSuperServiceImplClass(null);
strategy.setSuperMapperClass(null);
mpg.setStrategy(strategy);
//包配置
PackageConfig pc = new PackageConfig();
pc.setParent("com.demo");
pc.setController("controller");
pc.setService("service");
pc.setServiceImpl("serviceImpl");
pc.setMapper("mapper");
pc.setEntity("entity");
pc.setXml("xml");
mpg.setPackageInfo(pc);
//执行生成
mpg.execute();
}
}
这段生成的代码是单表生成的,一次就生成一张表的内容,并且没有用模板的部分,所以有了封装版的。
封装代码结构:
GeneratorExecute (批量生成)
public class GeneratorExecute {
public static void main(String[] args) {
// 表名
new GeneratorFactory()
.setIncludeTables(new String[]{
"MS_HOUR_DATA",
"SiteInfo",
"ZDJK_EXHAUST_FLOW_DAY_DATA",
"ZDJK_EXHAUST_FLOW_HOUR_DATA",
"ZDJK_EXHAUST_POLLUTANT_DAY_DATA",
"ZDJK_EXHAUST_POLLUTANT_HOUR_DATA",
"ZDJK_POLLUTANT_CODING",
"ZDJK_WASTEWATER_FLOW_DAY_DATA",
"ZDJK_WASTEWATER_FLOW_HOUR_DATA",
"ZDJK_WASTEWATER_POLLUTANT_DAY_DATA",
"ZDJK_WASTEWATER_POLLUTANT_HOUR_DATA",
// "alarm_category",
// "vehicle",
// "company",
// "person",
// "terminal",
// "building",
// "cargo"
})
.setExcludeTables(new String[]{})
.execute();
}
}
GeneratorFactory (代码生成工厂)
public class GeneratorFactory {
private final static String BASE_PACKAGE_NAME = "com.hitotek.htvfactor.generator";
// private final static String MY_DIR = "/Users/z_true/Documents/IdeaProjects/htvehicle-api/vehicle-generator/src/main/java/";
private final static String MY_DIR = "E:\\gongsi\\HTV\\htvfactor\\src\\main\\java";
private final static String MY_AUTHOR = "xjh";
// private final static String SQL_DIVER_NAME = "com.mysql.jdbc.Driver";
private final static String SQL_DIVER_NAME = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
private final static String SQL_URL = "171.221.172.168:14332;databaseName=LT_share";
// private final static String SQL_URL = "ip.51demo.tech:55432";
private final static String JDBC = "sqlserver";
private final static String SQL_USERNAME = "userfort";
private final static String SQL_PASSWORD = "uft_34@8";
private final static String DATABASE_NAME = "LT_share";
private final static String DATABASE_SCHEMA = "dbo";
private final static DbType DB_TYPE = DbType.SQL_SERVER;
// private final static DbType DB_TYPE = DbType.MYSQL;
private static String[] includeTables;
private static String[] excludeTables;
private void domain(String[] includeTables, String[] excludeTables) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
gc.setOutputDir(MY_DIR); //生成文件的输出目录
gc.setAuthor(MY_AUTHOR); //作者
gc.setFileOverride(true); //是否覆蓋已有文件 默认值:false
gc.setOpen(false); //是否打开输出目录 默认值:true
gc.setDateType(DateType.ONLY_DATE);
gc.setIdType(IdType.AUTO);
// gc.setSwagger2(true); //开启 swagger2 模式 默认false
gc.setBaseColumnList(true); //开启 baseColumnList 默认false
gc.setBaseResultMap(true); //开启 BaseResultMap 默认false
// gc.setEntityName("%sEntity"); //实体命名方式 默认值:null 例如:%sEntity 生成 UserEntity
// gc.setMapperName("%sMapper"); //mapper 命名方式 默认值:null 例如:%sDao 生成 UserDao
// gc.setXmlName("%sMapper"); //Mapper xml 命名方式 默认值:null 例如:%sDao 生成 UserDao.xml
// gc.setServiceName("%sService"); //service 命名方式 默认值:null 例如:%sBusiness 生成 UserBusiness
// gc.setServiceImplName("%sServiceImpl"); //service impl 命名方式 默认值:null 例如:%sBusinessImpl 生成 UserBusinessImpl
// gc.setControllerName("%sCrudController"); //controller 命名方式 默认值:null 例如:%sAction 生成 UserAction
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setDbType(DB_TYPE); //数据库类型 该类内置了常用的数据库类型【必须】
// dsc.setUrl("jdbc:" + JDBC + "://" + SQL_URL + "/" + DATABASE_NAME + "?useSSL=false&serverTimezone=Asia/Shanghai&characterEncoding=utf8" );
// dsc.setUrl("jdbc:" + JDBC + "://" + SQL_URL + "/" + DATABASE_NAME );
dsc.setUrl("jdbc:" + JDBC + "://" + SQL_URL);
System.out.println("输出地址");
System.out.println(dsc.getUrl());
dsc.setSchemaName(DATABASE_SCHEMA);
dsc.setDriverName(SQL_DIVER_NAME);
dsc.setUsername(SQL_USERNAME);
dsc.setPassword(SQL_PASSWORD);
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
// pc.setModuleName(scanner("模块名"));
pc.setParent(BASE_PACKAGE_NAME);
mpg.setPackageInfo(pc);
// 自定义模板配置
TemplateConfig tc = new TemplateConfig();
tc.setController("/templates/myController.java");
tc.setEntity("/templates/myEntity.java");
mpg.setTemplate(tc);
// 策略配置 数据库表配置,通过该配置,可指定需要生成哪些表或者排除哪些表
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.no_change); //表名生成策略
strategy.setColumnNaming(NamingStrategy.no_change);//数据库表字段映射到实体的命名策略, 未指定按照 naming 执行
// strategy.setCapitalMode(true); // 全局大写命名 ORACLE 注意
// strategy.setTablePrefix("prefix"); //表前缀
// strategy.setSuperEntityClass("com.baomidou.ant.common.BaseEntity"); //自定义继承的Entity类全称,带包名
// strategy.setSuperEntityColumns(new String[] { "test_id", "age" }); //自定义实体,公共字段
strategy.setEntityLombokModel(true); //【实体】是否为lombok模型(默认 false
strategy.setRestControllerStyle(true); //生成 @RestController 控制器
// strategy.setSuperControllerClass("com.baomidou.ant.common.BaseController"); //自定义继承的Controller类全称,带包名
// strategy.setInclude(tableName); //需要包含的表名,允许正则表达式(与exclude二选一配置)
strategy.setInclude(includeTables); // 需要生成的表可以多张表
strategy.setExclude(excludeTables); // 排除生成的表
strategy.setControllerMappingHyphenStyle(true); //驼峰转连字符
strategy.setTablePrefix(pc.getModuleName() + "_"); //是否生成实体时,生成字段注解
mpg.setStrategy(strategy);
// 选择 freemarker 引擎,默认 Veloctiy
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
public GeneratorFactory setIncludeTables(String[] tableNames) {
GeneratorFactory.includeTables = tableNames;
return this;
}
public GeneratorFactory setExcludeTables(String[] tableNames) {
GeneratorFactory.excludeTables = tableNames;
return this;
}
public void execute() {
if (null == includeTables) {
includeTables = new String[0];
}
if (null == excludeTables) {
excludeTables = new String[0];
}
this.domain(includeTables, excludeTables);
log.info("Generator Executed Success");
}
}
myController.java.ftl (Controller模板)
package ${package.Controller};
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import com.hitotek.support.v1.vo.RestQueryWrapper;
import com.hitotek.support.v1.core.AbstractRestSupport;
import com.hitotek.htvfactor.generator.entity.${entity};
import core.Data;
import com.hitotek.htvfactor.generator.service.I${entity}Service;
import org.springframework.web.bind.annotation.*;
<#if restControllerStyle>
import org.springframework.web.bind.annotation.RestController;
<#else>
import org.springframework.stereotype.Controller;
</#if>
<#if superControllerClassPackage??>
import ${superControllerClassPackage};
</#if>
/**
* <p>
<#-- * ${table.comment!} controller-->
* controller
* </p>
*
* @author ${author}
* @since ${date}
*/
<#if restControllerStyle>
@RestController
<#else>
@Controller
</#if>
@RequestMapping("<#if 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} extends AbstractRestSupport<${entity}, I${entity}Service> {
</#if>
@Override
protected Class<${entity}> clazz() {
return ${entity}.class;
}
@GetMapping
@Override
public ResponseEntity<Data> queryByPagination(RestQueryWrapper queryWrapper) {
return super.queryByPagination(queryWrapper);
}
@GetMapping("/{primaryKey}")
@Override
public ResponseEntity<Data> queryById(@PathVariable Long primaryKey) {
return super.queryById(primaryKey);
}
@DeleteMapping("/{primaryKey}")
@Override
public ResponseEntity<Data> deleteById(@PathVariable Long primaryKey) {
return super.deleteById(primaryKey);
}
@PatchMapping
@Override
public ResponseEntity<Data> updateById(@RequestBody ${entity} entity) {
return super.updateById(entity);
}
@PostMapping
@Override
public ResponseEntity<Data> create(@RequestBody ${entity} entity, BindingResult bindingResult) {
return super.create(entity, bindingResult, null);
}
}
</#if>
myEntity.java.ftl (实体类模板)
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;
import lombok.experimental.Accessors;
</#if>
import com.baomidou.mybatisplus.annotation.TableName;
/**
* ${table.comment!}
*
* @author ${author}
* @since ${date}
*/
<#if entityLombokModel>
@Data
<#if superEntityClass??>
@EqualsAndHashCode(callSuper = true)
<#else>
@EqualsAndHashCode(callSuper = false)
</#if>
@Accessors(chain = true)
</#if>
<#if swagger2>
@ApiModel(value="${entity}对象", description="${table.comment!}")
</#if>
@TableName(value = "${table.name}")
<#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.name}", type = IdType.AUTO)
<#elseif idType??>
@TableId(value = "${field.name}", type = IdType.${idType})
<#elseif field.convert>
@TableId("${field.name}")
</#if>
<#-- 普通字段 -->
<#elseif field.fill??>
<#-- ----- 存在字段填充设置 ----->
<#if field.convert>
@TableField(value = "${field.name}", fill = FieldFill.${field.fill})
<#else>
@TableField(fill = FieldFill.${field.fill})
</#if>
<#elseif field.convert>
@TableField("${field.name}")
</#if>
<#-- 乐观锁注解 -->
<#if (versionFieldName!"") == field.name>
@Version
</#if>
<#-- 逻辑删除注解 -->
<#if (logicDeleteFieldName!"") == field.name>
@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 entityBuilderModel>
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 entityBuilderModel>
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>
}
需要依赖:
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.30</version>
</dependency>
连接依赖:(可以更换)
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<scope>runtime</scope>
</dependency>
部分的公司依赖:
<dependency>
<groupId>com.disware</groupId>
<artifactId>genius-config</artifactId>
<version>${genius.version}</version>
</dependency>
<dependency>
<groupId>com.hitotek</groupId>
<artifactId>support-rest</artifactId>
<version>1.0.0-20200710.090640-4</version>
</dependency>
<dependency>
<groupId>com.hitotek</groupId>
<artifactId>logging-core</artifactId>
<version>${logging.version}</version>
</dependency>
<dependency>
<groupId>com.disware</groupId>
<artifactId>multipart-core</artifactId>
<version>${mulitpart.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>