生成类
package com.lbdj.user.service;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.lbdj.user.service.common.utils.EnhanceVelocityTemplateEngine;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class CodeGenerator {
public static void main(String[] args) {
// 数据源配置
FastAutoGenerator.create("jdbc:mysql://000.000.000.00:0000/lbdj?useUnicode=true&characterEncoding=utf8&useSSL=true&", "root", "root")
.globalConfig(builder -> {
// 设置作者
builder.author("作者")
//开启 swagger 模式 默认值:false
//.enableSwagger()
//禁止打开输出目录 默认值:true
.disableOpenDir()
//注释日期
.commentDate("yyyy-MM-dd")
//定义生成的实体类中日期类型 DateType.ONLY_DATE 默认值: DateType.TIME_PACK
.dateType(DateType.ONLY_DATE)
.outputDir(System.getProperty("user.dir")+"/src/main/java"); // 指定输出目录
})
.packageConfig(builder -> {
builder.parent("com.lbdj.user.service") // 父包模块名
.controller("controller") //Controller 包名 默认值:controller
.entity("entity") //Entity 包名 默认值:entity
.service("service") //Service 包名 默认值:service
.serviceImpl("service.impl")
.mapper("mapper") //Mapper 包名 默认值:mapper
.other("dto") // 设置dto包名
//.moduleName("xxx") // 设置父包模块名 默认值:无
.pathInfo(Collections.singletonMap(OutputFile.xml, System.getProperty("user.dir")+"/src/main/resources/mybatis/mapper")); // 设置mapperXml生成路径
//默认存放在mapper的xml下
})
.injectionConfig(consumer -> {
Map<String, String> customFile = new HashMap<>();
// DTO、VO
customFile.put("DTO.java", "/templates/entityDTO.java.vm");
//customFile.put("VO.java", "/templates/entityVO.java.ftl");
consumer.customFile(customFile);
})
.strategyConfig(builder -> {
// 设置需要生成的表名
//如果无法输入请修改idea配置:help -> Edit Custom VM Options -> 最后追加:-Deditable.java.test.console=true -> 重启idea
Scanner scanner = new Scanner(System.in);
System.out.println("请输入需要生成的表名,多个用逗号隔开:");
String tables = scanner.next();
scanner.close();
builder.addInclude(tables) // 设置需要生成的表名 可边长参数“user”, “user1”
//.addTablePrefix("tb_", "gms_") // 设置过滤表前缀
.serviceBuilder()//service策略配置
.formatServiceFileName("%sService")
.formatServiceImplFileName("%sServiceImpl")
.entityBuilder()// 实体类策略配置
//.idType(IdType.ASSIGN_ID)//主键策略 雪花算法自动生成的id
//.addTableFills(new Column("create_time", FieldFill.INSERT)) // 自动填充配置
//.addTableFills(new Property("update_time", FieldFill.INSERT_UPDATE))
.enableLombok() //开启lombok
.logicDeleteColumnName("deleted")// 说明逻辑删除是哪个字段
.enableTableFieldAnnotation()// 属性加上注解说明
.controllerBuilder() //controller 策略配置
.formatFileName("%sController")
.enableRestStyle() // 开启RestController注解
.mapperBuilder()// mapper策略配置
.formatMapperFileName("%sMapper")
.enableMapperAnnotation()//@mapper注解开启
.formatXmlFileName("%sMapper");
})
// 使用Freemarker引擎模板,默认的是Velocity引擎模板
.templateEngine(new EnhanceVelocityTemplateEngine())
.execute();
}
}
package com.lbdj.user.service.common.utils;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine;
import java.io.File;
import java.util.Map;
public class EnhanceVelocityTemplateEngine extends VelocityTemplateEngine {
@Override
protected void outputCustomFile(Map<String, String> customFile,
TableInfo tableInfo, Map<String, Object> objectMap) {
// 可以调用 tableInfo 的getFieldNames方法获得所有的列
this.printTableColumn(tableInfo);
// objectMap 里的key可以在ftl文件中直接引用
String entityName = tableInfo.getEntityName();
String otherPath = this.getPathInfo(OutputFile.other);
customFile.forEach((key, value) -> {
// 拼接路径
String fileName = String.format(otherPath + File.separator + entityName + "%s", key);
this.outputFile(new File(fileName), objectMap, value);
});
}
/**
* 获得所有的表列名
*
* @param tableInfo 表信息
*/
private void printTableColumn(TableInfo tableInfo) {
}
}
生成模板,放在resources/templates文件夹里
controller.java.vm
package ${package.Controller};
#set($entity = ${entity})
#set($lowerCaseEntity = $entity.substring(0,1).toLowerCase() + $entity.substring(1))
import org.springframework.web.bind.annotation.RequestMapping;
import ${package.Parent}.common.constant.NumberCons;
import ${package.Parent}.dto.${entity}DTO;
import ${package.Parent}.common.advice.exception.RRException;
import org.springframework.util.CollectionUtils;
import java.util.List;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.beans.factory.annotation.Autowired;
import ${package.Parent}.service.${entity}Service;
#if(${restControllerStyle})
import org.springframework.web.bind.annotation.RestController;
#else
import org.springframework.stereotype.Controller;
#end
#if(${superControllerClassPackage})
import ${superControllerClassPackage};
#end
/**
* $!{table.comment} 前端控制器
*
* @author ${author}
* @since ${date}
*/
#if(${restControllerStyle})
@RestController
#else
@Controller
#end
@RequestMapping("#if(${package.ModuleName})/${package.ModuleName}#end/#if(${controllerMappingHyphenStyle})${controllerMappingHyphen}#else${table.entityPath}#end")
#if(${kotlin})
class ${table.controllerName}#if(${superControllerClass}) : ${superControllerClass}()#end
#else
#if(${superControllerClass})
public class ${table.controllerName} extends ${superControllerClass} {
#else
public class ${table.controllerName} {
#end
@Autowired
private ${entity}Service ${lowerCaseEntity}Service;
/**
* 公共查询List
* @param request
* @return 返回多条信息
*/
@PostMapping("/selectList")
public List<${entity}DTO> selectList(@RequestBody ${entity}DTO request) {
Integer limit = request.getLimit();
if (null == limit) {
request.setLimit(NumberCons.TWENTY);
}
List<${entity}DTO> result = ${lowerCaseEntity}Service.selectBase(request);
return result;
}
/**
* 公共查询One
* @param request
* @return 返回一条信息
*/
@PostMapping("/selectOne")
public ${entity}DTO selectOne(@RequestBody ${entity}DTO request) {
request.setLimit(NumberCons.TWO);
List<${entity}DTO> result = ${lowerCaseEntity}Service.selectBase(request);
if (CollectionUtils.isEmpty(result)) {
return null;
}
if (result.size() > NumberCons.ONE) {
throw new RRException("记录存在多条!");
}
return result.get(NumberCons.zero);
}
}
#end
entity.java.vm
package ${package.Entity};
#foreach($pkg in ${table.importPackages})
import ${pkg};
#end
#if(${swagger})
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
#end
#if(${entityLombokModel})
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
#if(${chainModel})
import lombok.experimental.Accessors;
#end
#end
/**
* $!{table.comment}
*
* @author ${author}
* @since ${date}
*/
#if(${entityLombokModel})
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
#if(${chainModel})
@Accessors(chain = true)
#end
#end
#if(${table.convert})
@TableName("${schemaName}${table.name}")
#end
#if(${swagger})
@ApiModel(value = "${entity}对象", description = "$!{table.comment}")
#end
#if(${superEntityClass})
public class ${entity} extends ${superEntityClass}#if(${activeRecord})<${entity}>#end {
#elseif(${activeRecord})
public class ${entity} extends Model<${entity}> {
#elseif(${entitySerialVersionUID})
public class ${entity} implements Serializable {
#else
public class ${entity} {
#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" != "")
#if(${swagger})
@ApiModelProperty("${field.comment}")
#else
/**
* ${field.comment}
*/
#end
#end
#if(${field.keyFlag})
## 主键
#if(${field.keyIdentityFlag})
@TableId(value = "${field.annotationColumnName}", type = IdType.AUTO)
#elseif(!$null.isNull(${idType}) && "$!idType" != "")
@TableId(value = "${field.annotationColumnName}", type = IdType.${idType})
#elseif(${field.convert})
@TableId("${field.annotationColumnName}")
#end
## 普通字段
#elseif(${field.fill})
## ----- 存在字段填充设置 -----
#if(${field.convert})
@TableField(value = "${field.annotationColumnName}", fill = FieldFill.${field.fill})
#else
@TableField(fill = FieldFill.${field.fill})
#end
#elseif(${field.convert})
@TableField("${field.annotationColumnName}")
#end
## 乐观锁注解
#if(${field.versionField})
@Version
#end
## 逻辑删除注解
#if(${field.logicDeleteField})
@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(${chainModel})
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(${chainModel})
return this;
#end
}
#end
## --foreach end---
#end
## --end of #if(!${entityLombokModel})--
#if(${entityColumnConstant})
#foreach($field in ${table.fields})
public static final String ${field.name.toUpperCase()} = "${field.name}";
#end
#end
#if(${activeRecord})
@Override
public 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
}
entityDTO.java.vm
package ${package.Other};
#foreach($pkg in ${table.importPackages})
import ${pkg};
#end
#if(${swagger})
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
#end
import com.lbdj.toolkit.utils.ReturnField;
import com.lbdj.toolkit.utils.SFunction;
#if(${entityLombokModel})
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
#if(${chainModel})
import lombok.experimental.Accessors;
#end
#end
/**
* $!{table.comment} DTO
*
* @author ${author}
* @since ${date}
*/
#if(${entityLombokModel})
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
#if(${chainModel})
@Accessors(chain = true)
#end
#end
#if(${superEntityClass})
public class ${entity}DTO extends ${superEntityClass}#if(${activeRecord})<${entity}>#end {
#elseif(${activeRecord})
public class ${entity}DTO extends Model<${entity}> {
#elseif(${entitySerialVersionUID})
public class ${entity}DTO implements Serializable {
#else
public class ${entity}DTO {
#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" != "")
#if(${swagger})
@ApiModelProperty("${field.comment}")
#else
/**
* ${field.comment}
*/
#end
#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(${chainModel})
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(${chainModel})
return this;
#end
}
#end
## --foreach end---
#end
## --end of #if(!${entityLombokModel})--
#if(${entityColumnConstant})
#foreach($field in ${table.fields})
public static final String ${field.name.toUpperCase()} = "${field.name}";
#end
#end
/**
* 查询条数
*/
private Integer limit;
/**
* 需要返回的列(DTO列名)
*/
private String columnStr;
public <T> void setReturnField(SFunction<T, ?>... columns) {
this.columnStr = ReturnField.select(columns);
}
#if(${activeRecord})
@Override
public 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
}
mapper.java.vm
package ${package.Mapper};
import ${package.Entity}.${entity};
import com.github.yulichang.base.MPJBaseMapper;
#if(${mapperAnnotation})
import org.apache.ibatis.annotations.Mapper;
#end
/**
* $!{table.comment} Mapper 接口
*
* @author ${author}
* @since ${date}
*/
#if(${mapperAnnotation})
@Mapper
#end
#if(${kotlin})
interface ${table.mapperName} : ${superMapperClass}<${entity}>
#else
public interface ${table.mapperName} extends MPJBaseMapper<${entity}> {
}
#end
service.java.vm
package ${package.Service};
import ${package.Entity}.${entity};
import ${package.Parent}.dto.${entity}DTO;
import java.util.List;
import com.github.yulichang.base.MPJBaseService;
/**
* $!{table.comment} 服务类
*
* @author ${author}
* @since ${date}
*/
#if(${kotlin})
interface ${table.serviceName} : ${superServiceClass}<${entity}>
#else
public interface ${table.serviceName} extends MPJBaseService<${entity}> {
List<${entity}DTO> selectBase(${entity}DTO request);
}
#end
serviceImpl.java.vm
package ${package.ServiceImpl};
import ${package.Entity}.${entity};
import ${package.Mapper}.${table.mapperName};
import ${package.Service}.${table.serviceName};
import ${package.Parent}.dto.${entity}DTO;
import org.springframework.stereotype.Service;
import com.github.yulichang.base.MPJBaseServiceImpl;
import ${package.Parent}.common.utils.InitCommonQueryUtils;
import ${package.Parent}.common.utils.BeanConvertUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.util.CollectionUtils;
import java.util.Arrays;
import java.util.List;
/**
* $!{table.comment} 服务实现类
*
* @author ${author}
* @since ${date}
*/
@Service
#if(${kotlin})
open class ${table.serviceImplName} : ${superServiceImplClass}<${table.mapperName}, ${entity}>(), ${table.serviceName} {
}
#else
public class ${table.serviceImplName}
extends MPJBaseServiceImpl<${table.mapperName}, ${entity}>
implements ${table.serviceName} {
@Override
public List<${entity}DTO> selectBase(${entity}DTO request) {
${entity} convert = BeanConvertUtils.convert(request, ${entity}::new, null);
QueryWrapper<${entity}> queryWrapper = new QueryWrapper<>();
//封装返回字段&查询条件
InitCommonQueryUtils.initQuery(convert, request.getColumnStr(), queryWrapper);
queryWrapper.last(" limit " + request.getLimit());
List<${entity}> result = list(queryWrapper);
if (CollectionUtils.isEmpty(result)) {
return Arrays.asList();
}
return BeanConvertUtils.convertList(result, ${entity}DTO::new);
}
}
#end