代码如下:
package com.xiao.permission_system.generator;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.BeetlTemplateEngine;
import java.util.ArrayList;
import java.util.List;
/**
* @author beth
* @data 2019-09-12 09:33
*/
public class CodeGenerator {
/**
* 生成代码
*/
private static void generateCode() {
// 项目路径
String projectPath = System.getProperty("user.dir");
// 生成文件人
String author = "beth";
// 数据库连接信息
String url = "jdbc:mysql://localhost/permission_system?useUnicode=true&useSSL=false&characterEncoding=utf8";
String driverName = "com.mysql.cj.jdbc.Driver";
String username = "root";
String password = "000000";
// 父包名
String parentPackage = "com.xiao.permission_system";
// 实体类输出包
String entityPackage = "entity";
// mapper输出包
String mapperPackage = "mapper";
// service输出包
String servicePackage = "service";
// serviceImpl输出包
String serviceImplPackage = "service.impl";
// controller输出包
String controllerPackage = "controller";
// entity输出模版
String entityTemplate = "templates/entity.java";
// service输出模版
String serviceTemplate = "templates/service.java";
// mapper输出模版
String mapperTemplate = "templates/mapper.java";
// controller输出模版
String controllerTemplate = "templates/controller.java";
// 父类实体
String baseEntity = "com.xiao.permission_system.common.BaseEntity";
// 父类控制器
String baseController = "com.xiao.permission_system.common.BaseController";
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor(author);
gc.setOpen(false);
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl(url);
dsc.setDriverName(driverName);
dsc.setUsername(username);
dsc.setPassword(password);
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
//pc.setModuleName(scanner("模块名"));
pc.setParent(parentPackage);
pc.setEntity(entityPackage);
pc.setMapper(mapperPackage);
pc.setService(servicePackage);
pc.setServiceImpl(serviceImplPackage);
pc.setController(controllerPackage);
mpg.setPackageInfo(pc);
// 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
// 如果模板引擎是 freemarker
String templatePath = "/templates/mapper.xml.btl";
// 自定义输出配置
List<FileOutConfig> focList = new ArrayList<>();
// 自定义配置会被优先输出
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()
+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
templateConfig.setEntity(entityTemplate);
templateConfig.setService(serviceTemplate);
templateConfig.setMapper(mapperTemplate);
templateConfig.setController(controllerTemplate);
templateConfig.setXml(null);
mpg.setTemplate(templateConfig);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setSuperEntityClass(baseEntity);
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
strategy.setSuperControllerClass(baseController);
strategy.setSuperEntityColumns("id");
strategy.setControllerMappingHyphenStyle(true);
strategy.setTablePrefix( "sys_");
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new BeetlTemplateEngine());
mpg.execute();
}
public static void main(String[] args) {
generateCode();
}
}
1、Mybatis Plus默认有三种生成代码的模版引擎。 Velocity(默认)、Freemarker、Beetl
2、以上三种模版引擎分别对应如下模版,如果没有在代码中指定自己的模版,则系统默认用以下的模版。如果模板引擎是 freemarker,则文件后缀为ftl,如果模板引擎是velocity,则模版后缀为.vm,如果模板引擎是Beetl,则模版后缀为.btl
3、使用自己的模板, 在代码中指定自定义模板路径即可。
4、使用Beetl的自定义模版
package ${package.Controller};
import com.xiao.permission_system.service.${table.serviceName};
import org.springframework.beans.factory.annotation.Autowired;
import io.swagger.annotations.ApiOperation;
import com.xiao.permission_system.entity.${table.entityName};
import org.springframework.web.bind.annotation.*;
<% if(restControllerStyle){ %>
import org.springframework.web.bind.annotation.RestController;
<% }else{ %>
import org.springframework.stereotype.Controller;
<% } %>
<% if(isNotEmpty(superControllerClassPackage)){ %>
import ${superControllerClassPackage};
<% } %>
/**
* <p>
* ${table.comment!} 前端控制器
* </p>
*
* @author ${author}
* @since ${date}
*/
<% if(restControllerStyle){ %>
@RestController
<% }else{ %>
@Controller
<% } %>
@RequestMapping("<% if(isNotEmpty(package.ModuleName)){ %>/${package.ModuleName}<% } %>/<% if(isNotEmpty(controllerMappingHyphenStyle)){ %>${controllerMappingHyphen}<% }else{ %>${table.entityPath}<% } %>")
<% if(kotlin){ %>
class ${table.controllerName}<% if(isNotEmpty(superControllerClass)){ %> : ${superControllerClass}()<% } %>
<% }else{ %>
<% if(isNotEmpty(superControllerClass)){ %>
public class ${table.controllerName} extends ${superControllerClass} {
<% }else{ %>
public class ${table.controllerName} {
<% } %>
@Autowired
private ${table.serviceName} i${table.entityName}Service;
/**
* 新增
*/
@ApiOperation(value = "新增数据")
@RequestMapping(value = "/add", method = RequestMethod.POST)
public int add(@RequestBody ${entity} entity){
return i${table.entityName}Service.insert(entity);
}
/**
* 删除
*/
@ApiOperation(value = "删除数据")
@RequestMapping(value = "/del")
public int delete(@RequestParam("id") String id){
Integer result = i${table.entityName}Service.deleteById(id);
return result;
}
/**
* 查询
*/
@ApiOperation(value = "根据ID查询")
@RequestMapping(value = "/selectById")
public ${entity} selectById(@RequestParam("id") String id){
${entity} result = i${table.entityName}Service.selectById(id);
return result;
}
}
<% } %>
package ${package.Entity};
<% for(pkg in table.importPackages){ %>
import ${pkg};
<% } %>
<% if(swagger2){ %>
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
<% } %>
<% if(entityLombokModel){ %>
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
<% } %>
/**
* <p>
* ${table.comment!}
* </p>
*
* @author ${author}
* @since ${date}
*/
<% if(entityLombokModel){ %>
@Data
<% if(isNotEmpty(superEntityClass)){ %>
@EqualsAndHashCode(callSuper = true)
<% }else{ %>
@EqualsAndHashCode(callSuper = false)
<% } %>
@Accessors(chain = true)
<% } %>
<% if(table.convert){ %>
@TableName("${table.name}")
<% } %>
<% if(swagger2){ %>
@ApiModel(value="${entity}对象", description="${table.comment!''}")
<% } %>
<% if(isNotEmpty(superEntityClass)){ %>
public class ${entity} extends ${superEntityClass}<% if(activeRecord){ %><${entity}><%}%>{
<% }else if(activeRecord){ %>
public class ${entity} extends Model<${entity}> {
<% }else{ %>
public class ${entity} implements Serializable {
<% } %>
<% if(entitySerialVersionUID){ %>
private static final long serialVersionUID = 1L;
<% } %>
<% /** -----------BEGIN 字段循环遍历----------- **/ %>
<% for(field in table.fields){ %>
<%
if(field.keyFlag){
var keyPropertyName = field.propertyName;
}
%>
<% if(isNotEmpty(field.comment)){ %>
<% if(swagger2){ %>
@ApiModelProperty(value = "${field.comment}")
<% }else{ %>
/**
* ${field.comment}
*/
<% } %>
<% } %>
<% if(field.keyFlag){ %>
<%
/*主键*/
%>
<% if(field.keyIdentityFlag){ %>
@TableId(value = "${field.name}", type = IdType.AUTO)
<% }else if(isNotEmpty(idType)){ %>
@TableId(value = "${field.name}", type = IdType.${idType})
<% }else if(field.convert){ %>
@TableId("${field.name}")
<% } %>
<%
/*普通字段*/
%>
<% }else if(isNotEmpty(field.fill)){ %>
<% if(field.convert){ %>
@TableField(value = "${field.name}", fill = FieldFill.${field.fill})
<% }else{ %>
@TableField(fill = FieldFill.${field.fill})
<% } %>
<% }else if(field.convert){ %>
@TableField("${field.name}")
<% } %>
<%
/*乐观锁注解*/
%>
<% if(versionFieldName!'' == field.name){ %>
@Version
<% } %>
<%
/*逻辑删除注解*/
%>
<% if(logicDeleteFieldName!'' == field.name){ %>
@TableLogic
<% } %>
private ${field.propertyType} ${field.propertyName};
<% } %>
<% /** -----------END 字段循环遍历----------- **/ %>
<% if(!entityLombokModel){ %>
<% for(field in table.fields){ %>
<%
var getprefix ='';
if(field.propertyType=='boolean'){
getprefix='is';
}else{
getprefix='get';
}
%>
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}) {
<% } %>
this.${field.propertyName} = ${field.propertyName};
<% if(entityBuilderModel){ %>
return this;
<% } %>
}
<% } %>
<% } %>
<% if(entityColumnConstant){ %>
<% for(field in table.fields){ %>
public static final String ${strutil.toUpperCase(field.name)} = "${field.name}";
<% } %>
<% } %>
<% if(activeRecord){ %>
@Override
protected Serializable pkVal() {
<% if(isNotEmpty(keyPropertyName)){ %>
return this.${keyPropertyName};
<% }else{ %>
return null;
<% } %>
}
<% } %>
<% if(!entityLombokModel){ %>
@Override
public String toString() {
return "${entity}{" +
<% for(field in table.fields){ %>
<% if(fieldLP.index==0){ %>
"${field.propertyName}=" + ${field.propertyName} +
<% }else{ %>
", ${field.propertyName}=" + ${field.propertyName} +
<% } %>
<% } %>
"}";
}
<% } %>
}
package ${package.Mapper};
import ${package.Entity}.${entity};
import ${superMapperClassPackage};
import org.springframework.stereotype.Repository;
/**
* <p>
* ${table.comment!} Mapper 接口
* </p>
*
* @author ${author}
* @since ${date}
*/
<% if(kotlin){ %>
interface ${table.mapperName} : ${superMapperClass}<${entity}>
<% }else{ %>
@Repository
public interface ${table.mapperName} extends ${superMapperClass}<${entity}> {
}
<% } %>
package ${package.Service};
import ${package.Entity}.${entity};
import ${superServiceClassPackage};
/**
* <p>
* ${table.comment!} 服务类
* </p>
*
* @author ${author}
* @since ${date}
*/
<% if(kotlin){ %>
interface ${table.serviceName} : ${superServiceClass}<${entity}>
<% }else{ %>
public interface ${table.serviceName} extends ${superServiceClass}<${entity}> {
/**
* <p>
* 插入一条记录
* </p>
*
* @param entity 实体对象
* @return 插入成功记录数
*/
int insert(${entity} entity);
/**
* <p>
* 根据 ID 删除
* </p>
*
* @param id 主键ID
* @return 删除成功记录数
*/
int deleteById(String id);
/**
* <p>
* 根据 ID 查询
* </p>
*
* @param id 主键ID
* @return 实体
*/
${entity} selectById(String id);
}
<% } %>
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;
/**
* <p>
* ${table.comment!} 服务实现类
* </p>
*
* @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} {
@Autowired
private ${table.mapperName} ${table.mapperName};
/**
* <p>
* 插入一条记录
* </p>
*
* @param entity 实体对象
* @return 插入成功记录数
*/
public int insert(${entity} entity) {
Integer result = ${table.mapperName}.insert(entity);
return result;
}
/**
* <p>
* 根据 ID 删除
* </p>
*
* @param id 主键ID
* @return 删除成功记录数
*/
public int deleteById(String id) {
Integer result = ${table.mapperName}.deleteById(id);
return result;
}
/**
* <p>
* 根据 ID 查询
* </p>
*
* @param id 主键ID
* @return 实体
*/
public ${entity} selectById(String id){
${entity} result = ${table.mapperName}.selectById(id);
return result;
}
}
<% } %>