“This is the fifth day of my participation in the First Challenge 2022. For details: First Challenge 2022”

AutoGenerator code generator is based on Mybatis-Plus using the edited template to automatically generate code tools, generated code is to achieve a single table to add, delete, change and check, greatly improve our development efficiency, we only need to create a good table, add a good table notes, run the code generator, very convenient.

Main method for code generation

The code generation mainly includes five configurations, including global configuration, data source configuration, package configuration, policy configuration, and template configuration.

public static void main(String[] args) { AutoGenerator autoGenerator = new AutoGenerator(); / / global configuration autoGenerator. SetGlobalConfig (getGlobalConfig ()); / / data source configuration autoGenerator. SetDataSource (getDataSourceConfig ()); / / package configuration autoGenerator. SetPackageInfo (getPackageConfig ()); / / policy configuration autoGenerator. SetStrategy (getStrategyConfig ()); / / template configuration autoGenerator. SetTemplate (getTemplateConfig ()); autoGenerator.execute(); }Copy the code
Global configuration

Global configuration includes configuring the comments in the code, including the author and date comments, whether the entity uses the Swagger2 annotation and the primary key type of the entity, the path to generate the code, where the file will be generated after setting the path, and some global basic Settings

private static GlobalConfig getGlobalConfig() { GlobalConfig globalConfig = new GlobalConfig(); / / the AUTHOR globalConfig setAuthor (MyConfig. AUTHOR); String projectPath = System.getProperty("user.dir"); // Generate file directory String projectPath = System.getProperty("user.dir"); String filePath = projectPath + "/src/main/java/"; globalConfig.setOutputDir(filePath); // Set whether to open the globalconfig.setOpen (false) folder after the build file; // Entity attribute Swagger2 annotation GlobalConfig.setSwagger2 (true); / / overwrite files with the same, the default is false globalConfig setFileOverride (true); / / don't need to please to false globalConfig ActiveRecord characteristics. SetActiveRecord (false); The second level cache / / XML globalConfig. SetEnableCache (false); // XML ResultMap globalConfig.setBaseResultMap(false); // XML columnList globalConfig.setBaseColumnList(false); // set the DateType globalconfig.setdatetype (datetype.only_date); / / set globalConfig. SetIdType (IdType. AUTO); return globalConfig; }Copy the code
Data Source Configuration

Set the data source and database connection mode

private static DataSourceConfig getDataSourceConfig() {
    DataSourceConfig dataSourceConfig = new DataSourceConfig();
    dataSourceConfig.setDriverName("com.mysql.jdbc.Driver");
    dataSourceConfig.setUrl(MyConfig.DATA_SOURCE_URL);
    dataSourceConfig.setUsername(MyConfig.DATA_SOURCE_USER_NAME);
    dataSourceConfig.setPassword(MyConfig.DATA_SOURCE_PASSWORD);
    return dataSourceConfig;
}
Copy the code
Package configuration

Set the package names for the Controller, Service, DAO, and Entity layers and the location in the project, for example, com.penk.test.generator

private static PackageConfig getPackageConfig() { PackageConfig packageConfig = new PackageConfig(); / / set the MODULE name packageConfig. SetModuleName (MyConfig. The MODULE). / / PARENT packageConfig. SetParent (MyConfig. PARENT); / / store file package name packageConfig. SetController (" controller "); packageConfig.setEntity("entity"); packageConfig.setMapper("dao"); packageConfig.setService("service"); packageConfig.setServiceImpl("service.impl"); packageConfig.setXml("dao"); return packageConfig; }Copy the code
Policy configuration

Test_user and TEST_DEPT tables test_USER and TEST_DEPT tables test_dept tables test_user and TEST_DEPT tables test_dept tables Include can be set to {“test_user”,”test_dept”}, and if you want the generated code to remove the TablePrefix “test_”, you can set the TablePrefix value to “test_”, and the generated code will get the User and Dept entity classes.

private static StrategyConfig getStrategyConfig() { StrategyConfig strategy = new StrategyConfig(); // tablePrefix strategy.settableprefix (myconfig.tableprefix); // Database table name strategy.setinclude (myconfig.include); // Filename strategy.setNaming(namingStrategy. underline_to_camel); // Strategy. setColumnNaming(namingStrategy. underline_to_camel); // Strategy. setColumnNaming(namingStrategy. underline_to_camel); / / whether or not to use lombok simplify code strategy. SetEntityLombokModel (true); / / whether or not to use restful style strategy. SetRestControllerStyle (true); return strategy; }Copy the code
The template configuration

Customize the generated file template based on your own development habits. The template is as follows:

private static TemplateConfig getTemplateConfig() {
    TemplateConfig templateConfig = new TemplateConfig();
    templateConfig.setController("/templates-generator/controller.java.vm");
    templateConfig.setService("/templates-generator/service.java.vm");
    templateConfig.setServiceImpl("/templates-generator/serviceImpl.java.vm");
    templateConfig.setEntity("/templates-generator/entity.java.vm");
    templateConfig.setMapper("/templates-generator/mapper.java.vm");
    templateConfig.setXml("/templates-generator/mapper.xml.vm");
    return templateConfig;
}
Copy the code
controller.java.vm
package ${package.Controller}; import ${package.Entity}.${entity}; import ${package.Service}.${table.serviceName}; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; #if(${swagger2}) import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; #end #if(${restControllerStyle}) import org.springframework.web.bind.annotation.*; #else import org.springframework.stereotype.Controller; #end #if(${superControllerClassPackage}) import ${superControllerClassPackage}; #end import javax.annotation.Resource; import javax.validation.Valid; import java.util.HashMap; import java.util.Map; /** * @author ${author} * @since ${date} */ #if(${restControllerStyle}) @RestController #else @Controller #end @RequestMapping("/#if(${controllerMappingHyphenStyle})${controllerMappingHyphen}#else${table.entityPath}#end") #if(${swagger2}) @Api(tags = "$! ${table. ControllerName}#if(${superControllerClass}) : ${superControllerClass}()#end #else #if(${superControllerClass}) public class ${table.controllerName} extends ${superControllerClass} { #else public class ${table.controllerName} { #end @Resource private ${table.serviceName} ${table.entityPath}Service; @postmapping ("/save${entity}") @apiOperation (value = "save$! {table.comment}") public boolean save${entity}(@Valid @RequestBody ${entity} ${table.entityPath}) { return ${table.entityPath}Service.saveOrUpdate(${table.entityPath}); } @getMapping ("/delete${entity}") @apiOperation (value = "delete$! {table.comment}") public Boolean delete${entity}(@apiParam (" ID") @requestParam ${table.fields[0].propertyType} ID) { ${entity} ${table.entityPath} = new ${entity}(); ${table.entityPath}.setId(id); ${table.entityPath}.setDeleteFlag(1); return ${table.entityPath}Service.updateById(${table.entityPath}); } @postmapping ("/get${entity}List") @apiOperation (value = "query $! Public Map<String, Object> get${entity}List() {Map<String, Object> result = new HashMap<>(); IPage<${entity}> page = new Page<>(1, 10); ${table.entityPath}Service.page(page); result.put("list", page.getRecords()); result.put("total", page.getTotal()); return result; } } #endCopy the code
service.java.vm
package ${package.Service};

import ${superServiceClassPackage};
import ${package.Entity}.${entity};

/**
 * @author ${author}
 * @since ${date}
 */

#if(${kotlin})
interface ${table.serviceName} : ${superServiceClass}<${entity}>
#else
public interface ${table.serviceName} extends ${superServiceClass}<${entity}> {

}
#end
Copy the code
serviceImpl.java.vm
package ${package.ServiceImpl};

import ${superServiceImplClassPackage};
import ${package.Mapper}.${table.mapperName};
import ${package.Entity}.${entity};
import ${package.Service}.${table.serviceName};
import org.springframework.stereotype.Service;

/**
 * @author ${author}
 * @since ${date}
 */

@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} {

}
#end
Copy the code
entity.java.vm
package ${package.Entity}; #foreach($pkg in ${table.importPackages}) import ${pkg}; #end import com.baomidou.mybatisplus.annotation.*; #if(${swagger2}) import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; #end #if(${entityLombokModel}) import lombok.Data; #end /** * @author ${author} * @since ${date} */ #if(${entityLombokModel}) @Data #end @TableName("${table.name}") # if (${swagger2}) @ ApiModel (value = "${entity} object", the description = "$! {table.comment}") #end #if(${superEntityClass}) public class ${entity} extends ${superEntityClass}#if(${activeRecord})<${entity}>#end { #elseif(${activeRecord}) public class ${entity} extends Model<${entity}> { #else public class ${entity} implements Serializable { #end private static final long serialVersionUID = 1L; # # -- -- -- -- -- -- -- -- -- -- BEGIN field to iterate over -- -- -- -- -- -- -- -- -- -- # foreach ($field in ${table. The fields}) # if (${field. KeyFlag}) #set($keyPropertyName=${field.propertyName}) #end #if("$! field.comment" ! = "") #if(${swagger2}) @ApiModelProperty(value = "${field.comment.replaceAll("\n", "").replaceAll("\r", "")}") # else / ${field.com ment} * / * * * # # # end end the if (${field. KeyFlag}) # # # primary key if (${field. KeyIdentityFlag}) @TableId(value = "${field.name}", type = IdType.AUTO) #elseif(! $null.isNull(${idType}) && "$! idType" ! = "") @TableId(value = "${field.name}", ${field.convert}) @tableId ("${field.name}") #end # -- -- -- -- -- there is the fields set # -- -- -- -- -- the if (${field. The convert}) @ TableField (value = "${field. The name}", fill = FieldFill.${field.fill}) #else @TableField(fill = FieldFill.${field.fill}) #end #else If (${versionFieldName}==${field.name}) @version #end ## logicallydelete annotations #if(${logicDeleteFieldName}==${field.name}) @TableLogic #end private ${field.propertyType} ${field.propertyName}; #end ## ---------- end loop through ---------- #if(! ${entityLombokModel}) #foreach($field in ${table.fields}) #if(${field.propertyType.equals("boolean")}) #set($getprefix="is") #else #set($getprefix="get") #end 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}) { #end this.${field.propertyName}  = ${field.propertyName}; #if(${entityBuilderModel}) return this; #end } #end #end #if(${entityColumnConstant}) #foreach($field in ${table.fields}) public static final String ${field.name.toUpperCase()} = "${field.name}"; #end #end #if(${activeRecord}) @Override protected Serializable pkVal() { #if(${keyPropertyName}) return this.${keyPropertyName}; #else return null; #end } #end #if(! ${entityLombokModel}) @Override public String toString() { return "${entity}{" + #foreach($field in ${table.fields}) #if($! {foreach.index}==0) "${field.propertyName}=" + ${field.propertyName} + #else ", ${field.propertyName}=" + ${field.propertyName} + #end #end "}"; } #end }Copy the code
mapper.java.vm
package ${package.Mapper};

import ${superMapperClassPackage};
import ${package.Entity}.${entity};
import org.springframework.stereotype.Repository;

/**
 * @author ${author}
 * @since ${date}
 */

#if(${kotlin})
interface ${table.mapperName} : ${superMapperClass}<${entity}>
#else
@Repository
public interface ${table.mapperName} extends ${superMapperClass}<${entity}> {

}
#end
Copy the code
mapper.xml.vm
<? The XML version = "1.0" encoding = "utf-8"? > <! DOCTYPE mapper PUBLIC "- / / mybatis.org//DTD mapper / 3.0 / EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > < mapper namespace="${package.Mapper}.${table.mapperName}"> #if(${enableCache}) <! - open the second level cache - > < cache type = "org. Mybatis. Caches. Ehcache. LoggingEhcache" / > # # end the if (${baseResultMap}) <! ResultMap id="BaseResultMap" type="${package.Entity}.${Entity} "> #foreach($field in ${table.fields}) <id column="${field.name}" property="${field. name}" /> #end #end <result column="${field.name}" property="${field.name}" /> #end #foreach($field in ${table.fields}) #if(! ${field.keyFlag})## Generate a common column <result column="${field.name}" property="${field.propertyName}" /> #end #end </resultMap> #end  #if(${baseColumnList}) <! #foreach($field in ${table.column_list}) ${field.name}, #end ${table.fieldNames} </sql> #end </mapper>Copy the code