package com.xxx.codegen; import com.baomidou.mybatisplus.core.mapper.baseMapper; import com.baomidou.mybatisplus.generator.FastAutoGenerator; import com.baomidou.mybatisplus.generator.config.DataSourceConfig; import com.baomidou.mybatisplus.generator.config.OutputFile; import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert; import com.baomidou.mybatisplus.generator.config.po.TableInfo; import com.baomidou.mybatisplus.generator.config.querys.MySqlQuery; import com.baomidou.mybatisplus.generator.config.rules.DateType; import com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine; import com.baomidou.mybatisplus.generator.keywords.MySqlKeyWordsHandler; import java.io.File; import java.util.*; public class CurdGenerator { private static String author = "codegen"; private static String url = "jdbc:mysql://xxx.xx.x.xxx:3306/xxx-dev?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC"; private static String username = "xxx"; private static String password = "xxx"; //输出目录 private static String outputDir = System.getProperty("user.dir") + "/codegen/src/main/java"; //父包 private static String parentPackage = "com.xxx"; //模块名 private static String moduleName = "code"; //表名 private static String tableName = "all";//all表示所有 private static String tablePrefix = "sys_,doctor_,agent_,drug_,mer_,user_,doc,tms_,msg_"; // 表有无创建时间日期字段 private static boolean existDate = false; private static String createDateName = "createDate"; private static String updateDateName = "updateDate"; // 全局响应类名 private static String allResultApiName = "R"; // 处理 all 情况 protected static ListVM文件getTables(String tables) { return "all".equals(tables) ? Collections.emptyList() : Arrays.asList(tables.split(",")); } private static final DataSourceConfig.Builder DATA_SOURCE_ConFIG = new DataSourceConfig .Builder(url, username, password) //数据库查询 .dbQuery(new MySqlQuery()) //数据库类型转换器 .typeConvert(new MySqlTypeConvert()) //数据库关键字处理器 .keyWordsHandler(new MySqlKeyWordsHandler()); private static FastAutoGenerator fastAutoGenerator = FastAutoGenerator.create(DATA_SOURCE_CONFIG); public static void main(String[] args) { genCode(); } public static void globalConfig() { fastAutoGenerator.globalConfig(builder -> { // 设置作者 builder.author(author) // 开启 swagger 模式 .enableSwagger() // 覆盖已生成文件 .fileOverride() //禁止生成代码后自动d出输出目录 .disableOpenDir() // 时间策略 .dateType(DateType.TIME_PACK) //注释日期,默认值: yyyy-MM-dd .commentDate("yyyy-MM-dd") // 指定输出目录 .outputDir(outputDir); }); } public static void packageConfig() { fastAutoGenerator.packageConfig(builder -> { // 设置父包名 builder.parent(parentPackage) // 设置父包模块名 .moduleName(moduleName) .entity("po") // .service("service") .serviceImpl("service.impl") .mapper("mapper") .xml("mapper.xml") .controller("controller") //设置自定义的文件包名,默认是other,这边取消掉 .other("") // 设置mapperXml生成路径 .pathInfo(Collections.singletonMap(OutputFile.mapperXml, "codegen/src/main/resources/mapper")); }); } public static void templateConfig() { fastAutoGenerator.templateConfig((scanner, builder) -> builder .entity("/template/entity.java") .service("/template/service.java") .serviceImpl("/template/serviceImpl.java") .mapper("/template/mapper.java") .mapperXml("/template/mapper.xml") .controller("/template/controller.java") ); } public static void injectionConfig() { Map fileMap = new HashMap<>(); Map fieldMap = new HashMap<>(); fastAutoGenerator.injectionConfig(builder -> builder //输出文件之前消费者 .beforeOutputFile((tableInfo, objectMap) -> { String entityName = tableInfo.getEntityName(); Map aPackageMap = (Map) objectMap.get("package"); objectMap.put("table_name", entityName.substring(0, 1).toLowerCase() + entityName.substring(1)); objectMap.put("model", aPackageMap.get("Parent") + ".model"); objectMap.put("bean", entityName.replace("PO", "")); objectMap.put("vo", entityName + "VO"); objectMap.put("convert", entityName + "Convert"); objectMap.put("dto", entityName + "DTO"); objectMap.put("query", entityName + "Query"); objectMap.put("common", "com.shuke.common"); diyConfig(objectMap); //自定义生成文件配置 fileMap.put("/model/vo/" + entityName + "VO.java", "/template/vo.java.vm"); fileMap.put("/model/convert/" + entityName + "Convert.java", "/template/convert.java.vm"); fileMap.put("/model/dto/" + entityName + "DTO.java", "/template/dto.java.vm"); fileMap.put("/model/query/" + entityName + "Query.java", "/template/query.java.vm"); }) // 自定义属性,模板变量 .customMap(fieldMap) .customFile(fileMap) ); } private static void diyConfig(Map objectMap) { //设定entityLombokModel为true,使用lombok objectMap.put("entityLombokModel", true); //表有无创建时间日期字段 objectMap.put("existDate", existDate); //时间字段set方法定义 objectMap.put("setCreateDate", "set" + createDateName.substring(0, 1).toUpperCase() + createDateName.substring(1)); objectMap.put("setUpdateDate", "set" + updateDateName.substring(0, 1).toUpperCase() + updateDateName.substring(1)); objectMap.put("ApiResult", allResultApiName); objectMap.put("baseResultMap", true); objectMap.put("baseColumnList", true); } public static void strategyConfig() { fastAutoGenerator.strategyConfig(builder -> { // 设置需要生成的表名 builder.addInclude(getTables(tableName)) // 设置过滤表前缀 .addTablePrefix(tablePrefix) .entityBuilder() .enableLombok() .logicDeleteColumnName("is_deleted") .enableTableFieldAnnotation() .controllerBuilder() .enableRestStyle() .mapperBuilder() //生成通用的resultMap .enablebaseResultMap() .superClass(baseMapper.class); }); } public static void templateEngine() { fastAutoGenerator.templateEngine(new VelocityTemplateEngine() { @Override protected void outputCustomFile(Map customFile, TableInfo tableInfo, Map objectMap) { String otherPath = getPathInfo(OutputFile.other); customFile.forEach((key, value) -> { String fileName = String.format((otherPath + File.separator + "%s"), key); outputFile(new File(fileName), objectMap, value); }); customFile.clear(); } }); } public static void genCode() { globalConfig(); packageConfig(); templateConfig(); strategyConfig(); injectionConfig(); templateEngine(); fastAutoGenerator.execute(); } }
package $!{package.Controller}; import ${common}.${ApiResult}; #if(${swagger}) import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import springfox.documentation.annotations.ApiIgnore; #end import javax.annotation.Resource; import org.springframework.web.bind.annotation.*; import $!{package.Entity}.$!{entity}; import $!{package.Service}.$!{table.serviceName}; import $!{model}.dto.$!{dto}; import $!{model}.vo.$!{vo}; import $!{model}.query.$!{query}; import $!{model}.convert.$!{convert}; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import java.time.LocalDateTime; import java.util.Arrays; import java.util.List; import com.xxx.jdbc.PageInfo; #if(${restControllerStyle}) import org.springframework.web.bind.annotation.RestController; #else import org.springframework.stereotype.Controller; #end #if(${superControllerClassPackage}) import $!{superControllerClassPackage}; #end #if(${swagger}) @Api(value = "$!{table.comment}", tags = "$!{table.comment}") #end #if(${restControllerStyle}) @RestController #else @Controller #end @RequestMapping("${table_name}") #if(${kotlin}) class ${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_name}Service; #if(${swagger}) @ApiOperation(value = "获取$!{table.comment}分页列表", notes = "获取$!{table.comment}分页列表") @ApiImplicitParams({ @ApiImplicitParam(name = "current", required = false, value = "当前页", paramType = "form"), @ApiImplicitParam(name = "size", required = false, value = "当前页大小", paramType = "form") }) #end @GetMapping(value = "/list/page") public ${ApiResult}> list(#if(${swagger}) @ApiIgnore #end $!{query} query,#if(${swagger}) @ApiIgnore #end Page page) { IPage<$!{entity}> pageList = ${table_name}Service.getWithPage(page, query); PageInfo<$!{vo}> resultPage = $!{convert}.INSTANCE.toPageList(pageList); return ${ApiResult}.ok(resultPage); } #if(${swagger}) @ApiOperation(value = "根据ID获取$!{table.comment}详情", notes = "根据ID获取$!{table.comment}详情") #end @GetMapping("/get") public ${ApiResult}<$!{vo}> get(@RequestParam("id") Long id) { $!{entity} entity = ${table_name}Service.getById(id); $!{vo} vo = $!{convert}.toVo(entity); return ${ApiResult}.ok(vo); } #if(${swagger}) @ApiOperation(value = "新增${table.comment}", notes = "新增${table.comment}") @ApiImplicitParams({ #foreach($field in ${table.fields}) #if(!${field.keyFlag}) #if(${foreach.count}==${table.fields.size()}) @ApiImplicitParam(name = "${field.propertyName}", required = false, value = "${field.comment}", paramType = "form") #else @ApiImplicitParam(name = "${field.propertyName}", required = false, value = "${field.comment}", paramType = "form"), #end #end #end }) #end @PostMapping("/add") public ${ApiResult} add(#if(${swagger}) @ApiIgnore #end @RequestBody $!{dto} dto) { ${entity} po = ${bean}Convert.toPO(dto); #if(${existDate}) po.${setCreateDate}(LocalDateTime.now()); po.${setUpdateDate}(LocalDateTime.now()); #end boolean save = ${table_name}Service.save(po); return save ? ${ApiResult}.ok() : ${ApiResult}.failed(); } #if(${swagger}) @ApiOperation(value = "编辑${table.comment}", notes = "编辑${table.comment}") @ApiImplicitParams({ #foreach($field in ${table.fields}) #if(${foreach.count}==${table.fields.size()}) @ApiImplicitParam(name = "${field.propertyName}", required = false, value = "${field.comment}", paramType = "form") #else @ApiImplicitParam(name = "${field.propertyName}", required = false, value = "${field.comment}", paramType = "form"), #end #end }) #end @PostMapping("/update") public ${ApiResult} update(#if(${swagger}) @ApiIgnore #end @RequestBody $!{dto} dto) { ${entity} po = ${bean}Convert.toPO(dto); #if(${existDate}) po.${setUpdateDate}(LocalDateTime.now()); #end boolean update = ${table_name}Service.updateById(po); return update ? ${ApiResult}.ok() : ${ApiResult}.failed(); } ## ## #if(${swagger}) ## @ApiOperation(value = "移除$!{table.comment}", notes = "移除$!{table.comment}") ## @ApiImplicitParams({ ## @ApiImplicitParam(name = "id", required = true, value = "$!{table.comment}id", paramType = "form") ## }) ## #end ## @PostMapping("/remove") ## public ${ApiResult} remove(@RequestParam(value = "id") Long id) { ## boolean remove = ${table_name}Service.removeById(id); ## return remove ? ${ApiResult}.ok() : ${ApiResult}.failed(); ## } } #end
package $!{model}.convert; import $!{package.Entity}.$!{entity}; import ${model}.dto.$!{dto}; import ${model}.vo.$!{vo}; import java.util.ArrayList; import java.util.List; import org.mapstruct.Mapper; import org.mapstruct.factory.Mappers; import com.baomidou.mybatisplus.core.metadata.IPage; import com.xxx.jdbc.PageInfo; import org.mapstruct.ReportingPolicy; @Mapper(componentModel = "spring",unmappedSourcePolicy = ReportingPolicy.IGNORE, unmappedTargetPolicy = ReportingPolicy.IGNORE ) public interface $!{convert} { $!{entity} INSTANCE = Mappers.getMapper($!{entity}.class); $!{vo} toVo($!{entity} po); List<$!{vo}> toVo(List<$!{entity}> pos); $!{dto} toDto($!{entity} po); List<$!{dto}> toDto(List<$!{entity}> po); PageInfo<$!{vo}> toPageList(IPage<$!{entity}> pos); $!{entity} toPo($!{dto} dto); }
package $!{model}.dto; #if(${swagger}) import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; #end import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; #foreach($pkg in ${table.importPackages}) import $!{pkg}; #end @Data @NoArgsConstructor #if(${swagger}) @ApiModel(value="$!{table.comment}转换对象") #end public class $!{dto} implements Serializable { private static final long serialVersionUID = 1L; ## ---------- BEGIN 字段循环遍历 ---------- #foreach($field in ${table.fields}) #if(${field.keyFlag}) #set($keyPropertyName=${field.propertyName}) #end #if("$!field.comment" != "") #if(${swagger}) @ApiModelProperty(value = "$!{field.comment}") #else #end #end private $!{field.propertyType} $!{field.propertyName}; #end ## ---------- END 字段循环遍历 ---------- }
package $!{package.Entity}; #foreach($pkg in ${table.importPackages}) import $!{pkg}; #end #if(${entityLombokModel}) import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; #end #if(${entityLombokModel}) @Data #if(${superEntityClass}) @EqualsAndHashCode(callSuper = true) #else @EqualsAndHashCode(callSuper = false) #end @NoArgsConstructor #end #if(${table.convert}) @TableName("$!{table.name}") #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 #if(${entitySerialVersionUID}) private static final long serialVersionUID = 1L; #end ## ---------- BEGIN 字段循环遍历 ---------- #foreach($field in ${table.fields}) #if(${field.keyFlag}) #set($keyPropertyName=${field.propertyName}) #end #if("$!field.comment" != "") #end #if(${field.keyFlag}) ## 主键 #if(${field.keyIdentityFlag}) @TableId(value = "$!{field.name}", type = IdType.AUTO) #elseif(!$null.isNull(${idType}) && "$!idType" != "") @TableId(value = "$!{field.name}", type = IdType.$!{idType}) #elseif(${field.convert}) @TableId("$!{field.name}") #end ## 普通字段 #elseif(${field.fill}) ## ----- 存在字段填充设置 ----- #if(${field.convert}) @TableField(value = "$!{field.name}", fill = FieldFill.$!{field.fill}) #else @TableField(fill = FieldFill.$!{field.fill}) #end #elseif(${field.convert}) #end ## 乐观锁注解 #if(${versionFieldName}==${field.name}) @Version #end ## 逻辑删除注解 #if(${logicDeleteFieldName}==${field.name}) @TableLogic #end private $!{field.propertyType} $!{field.propertyName}; #end ## ---------- END 字段循环遍历 ---------- #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} "$!{field.propertyName}=" + $!{field.propertyName} + #else ", $!{field.propertyName}=" + $!{field.propertyName} + #end #end "}"; } #end }
package $!{package.Mapper}; import $!{package.Entity}.$!{entity}; import com.baomidou.mybatisplus.core.mapper.baseMapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import org.springframework.stereotype.Repository; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Options; import $!{model}.query.$!{query}; import org.apache.ibatis.annotations.Param; import java.util.List; #if(${kotlin}) interface $!{table.mapperName} : $!{superMapperClass}<$!{entity}> #else @Repository public interface $!{table.mapperName} extends $!{superMapperClass}<$!{entity}> { IPage<$!{entity}> getWithPage(Page page, @Param("query") $!{query} query); @Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id") Long insertReturnId(@Param("po") $!{entity} po); int getCountByQuery(@Param("query") ${query} query); $!{entity} getOneByQuery(@Param("query") ${query} query); List<$!{entity}> getAllByQuery(@Param("query") ${query} query); } #end
#if(${enableCache}) #end #if(${baseResultMap}) #foreach($field in ${table.fields}) #if(${field.keyFlag})##生成主键排在第一位 #end #if(${baseColumnList})#end #end #foreach($field in ${table.commonFields})##生成公共字段 #end #foreach($field in ${table.fields}) #if(!${field.keyFlag})##生成普通字段 #end #end #foreach($field in ${table.commonFields}) ${field.name}, #end ${table.fieldNames} #end${table.name} #set($i=${table.name.lastIndexOf('_')}) #set($alias=${table.name.substring($i+1)})${table.name} as ${alias}
package $!{model}.query; #if(${swagger}) import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; #end import lombok.Data; import lombok.NoArgsConstructor; #foreach($pkg in ${table.importPackages}) import $!{pkg}; #end @Data @NoArgsConstructor #if(${swagger}) @ApiModel(value="$!{table.comment}查询对象") #end public class $!{query} implements Serializable { private static final long serialVersionUID = 1L; ## ---------- BEGIN 字段循环遍历 ---------- #foreach($field in ${table.fields}) #if(${field.keyFlag}) #set($keyPropertyName=${field.propertyName}) #end #if("$!field.comment" != "") #if(${swagger}) @ApiModelProperty(value = "$!{field.comment}") #else #end #end private $!{field.propertyType} $!{field.propertyName}; #end ## ---------- END 字段循环遍历 ---------- }
package $!{package.Service}; import $!{package.Entity}.$!{entity}; import $!{superServiceClassPackage}; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.core.metadata.IPage; import $!{model}.dto.$!{dto}; import $!{model}.query.$!{query}; import java.util.List; #if($!{kotlin}) interface $!{table.serviceName} : $!{superServiceClass}<$!{entity}> #else public interface $!{table.serviceName} extends $!{superServiceClass}<$!{entity}> { IPage<$!{entity}> getWithPage(Page page, $!{query} query); $!{entity} getOneByQuery(${query} query); List<$!{entity}> getAllByQuery( ${query} query); } #end
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.transaction.annotation.Transactional; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import $!{model}.dto.$!{dto}; import $!{model}.vo.$!{vo}; import $!{model}.query.$!{query}; import java.util.List; @Service @Transactional(rollbackFor = Exception.class) #if($!{kotlin}) open class $!{table.serviceImplName} : $!{superServiceImplClass}<$!{table.mapperName}, $!{entity}>(), $!{table.serviceName} { } #else public class $!{table.serviceImplName} extends $!{superServiceImplClass}<$!{table.mapperName}, $!{entity}> { ## @Override public IPage<$!{entity}> getWithPage(Page page, $!{query} query) { return baseMapper.getWithPage(page, query); } ## @Override public $!{entity} getOneByQuery($!{query} query) { return baseMapper.getOneByQuery(query); } ## @Override public List<$!{entity}> getAllByQuery($!{query} query) { return baseMapper.getAllByQuery(query); } } #end
package $!{model}.vo; #if(${swagger}) import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; #end import lombok.Data; import lombok.NoArgsConstructor; #foreach($pkg in ${table.importPackages}) import $!{pkg}; #end @Data @NoArgsConstructor #if(${swagger}) @ApiModel(value="$!{vo}视图对象") #end public class $!{vo} implements Serializable { private static final long serialVersionUID = 1L; ## ---------- BEGIN 字段循环遍历 ---------- #foreach($field in ${table.fields}) #if(${field.keyFlag}) #set($keyPropertyName=${field.propertyName}) #end #if("$!field.comment" != "") #if(${swagger}) @ApiModelProperty(value = "$!{field.comment}") #else #end #end private $!{field.propertyType} $!{field.propertyName}; #end ## ---------- END 字段循环遍历 ---------- }properties文件
#u4EE3u7801u751Fu6210u5668uFF0Cu914Du7F6Eu4FE1u606F mainPath=com.xxx #u5305u540D package=com.xxx moduleName=generator #u4F5Cu8005 author=shuke code generator #u8868u524Du7F00(u7C7Bu540Du4E0Du4F1Au5305u542Bu8868u524Du7F00) tablePrefix=table_ #u7C7Bu578Bu8F6Cu6362uFF0Cu914Du7F6Eu4FE1u606F tinyint=Integer smallint=Integer mediumint=Integer int=Integer integer=Integer bigint=Long float=Float double=Double decimal=BigDecimal bit=Boolean char=String bpchar=String varchar=String tinytext=String text=String mediumtext=String longtext=String date=LocalDate datetime=LocalDateTime timestamp=LocalDateTime
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)