1、模板生成类:PlusGenerator.java
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.OracleTypeConvert;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.IColumnType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.MissingResourceException;
@Component
public class PlusGenerator {
private static final String DB_URL = "spring.datasource.druid.db1.url";
private static final String USER_NAME = "spring.datasource.druid.db1.username";
private static final String PASSWORD = "spring.datasource.druid.db1.password";
private static final String DRIVER_CLASS_NAME = "spring.datasource.druid.db1.driver-class-name";
private static Environment env;
@Autowired
public void set(Environment env) throws IOException {
PlusGenerator.env = env;
}
/**
* key不存在则返回null
* @param key
* @return
*/
public static String getString(String key) {
try {
return env.getProperty(key);
} catch (MissingResourceException e) {
return null;
}
}
/**
* @param author 作者
* @param packageName 包名
* @param dbType 数据库类型(mysql、oracle)
* @param tableName 表名
*/
public static void generatorByType(String author, String packageName,String dbType, String ... tableName) {
AutoGenerator mpg = new AutoGenerator();
// 选择 freemarker 引擎,默认 Veloctiy mpg.setTemplateEngine(new FreemarkerTemplateEngine());
// 全局配置
GlobalConfig gc = new GlobalConfig();
System.out.println(PlusGenerator.class.getClassLoader().getResource("").getPath()+ "/codeGenerator");
gc.setOutputDir(PlusGenerator.class.getClassLoader().getResource("").getPath()+ "/codeGenerator");
gc.setFileOverride(true);
// ActiveRecord特性
gc.setActiveRecord(true);
// XML 二级缓存
gc.setEnableCache(false);
//XML ResultMap
gc.setBaseResultMap(true);
//XML columList
gc.setBaseColumnList(true);
gc.setDateType(DateType.ONLY_DATE);
if(StringUtils.isBlank(author)){
author = "未知";
}
gc.setAuthor(author);
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setDbType(DbType.getDbType(dbType));
dsc.setTypeConvert(new OracleTypeConvert(){
// 自定义数据库表字段类型转换【可选】
@Override
public IColumnType processTypeConvert(GlobalConfig globalConfig, String fieldType) {
System.out.println("转换类型:" + fieldType);
// 注意!!processTypeConvert 存在默认类型转换,如果不是你要的效果请自定义返回、非如下直接返回。
return super.processTypeConvert(gc, fieldType);
}
});
dsc.setDriverName(getString(DRIVER_CLASS_NAME));
dsc.setUsername(getString(USER_NAME));
dsc.setPassword(getString(PASSWORD));
dsc.setUrl(getString(DB_URL));
mpg.setDataSource(dsc);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
// strategy.setCapitalMode(true);// 全局大写命名 ORACLE 注意
//strategy.setTablePrefix(new String[] { "tlog_", "tsys_" });// 此处可以修改为您的表前缀
strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略
strategy.setInclude(tableName); // 需要生成的表
mpg.setStrategy(strategy);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setParent(packageName);
pc.setController("controller");
pc.setEntity("persistence.entity");
pc.setMapper("persistence.mapper");
mpg.setPackageInfo(pc);
// 自定义模板配置,可以 copy 源码 mybatis-plus/src/main/resources/templates 下面内容修改,
// 放置自己项目的 src/main/resources/templates 目录下, 默认名称一下可以不配置,也可以自定义模板名称
TemplateConfig tc = new TemplateConfig();
tc.setController("/vm/controller.java.vm");
tc.setService("/vm/service.java.vm");
tc.setServiceImpl("/vm/serviceImpl.java.vm");
tc.setEntity("/vm/entity.java.vm");
tc.setMapper("/vm/mapper.java.vm");
// 如上任何一个模块如果设置 空 OR Null 将不生成该模块。
mpg.setTemplate(tc);
// 注入自定义配置,可以在 VM 中使用 cfg.abc 设置的值
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
Map map = new HashMap<>();
map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp");
this.setMap(map);
}
};
mpg.setCfg(cfg);
// 执行生成
mpg.execute();
// 打印注入设置【可无】
System.err.println("代码生成成功!!");
}
}
2、entity.java.vm
package ${package.Entity};
import java.io.Serializable;
import java.util.Date;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* @描述:$!{table.comment}
* @作者: ${author}
* @日期: ${date}
*/
@ApiModel(value="$!{table.comment}")
public class ${entity} 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" != "")
@ApiModelProperty(value = "${field.comment}")
#end
private ${field.propertyType} ${field.propertyName};
#end
#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
}
2、mapper.java.vm
package ${package.Mapper};
import ${package.Entity}.${entity};
import ${superMapperClassPackage};
/**
* @描述:$!{table.comment} Mapper 接口
* @作者: ${author}
* @日期: ${date}
*/
public interface ${table.mapperName} extends ${superMapperClass}<${entity}> {
}
3、service.java.vm
package ${package.Service};
import ${package.Entity}.${entity};
import ${superServiceClassPackage};
/**
* @描述:$!{table.comment} 服务类
* @作者: ${author}
* @日期: ${date}
*/
public interface ${table.serviceName} extends ${superServiceClass}<${entity}> {
}
4、serviceImpl.java.vm
package ${package.ServiceImpl};
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import ${package.Entity}.${entity};
import ${package.Mapper}.${table.mapperName};
import ${package.Service}.${table.serviceName};
import org.springframework.stereotype.Service;
/**
* @描述:$!{table.comment} 服务类
* @作者: ${author}
* @日期: ${date}
*/
@Service
public class ${table.serviceImplName} extends ${superServiceImplClass}<${table.mapperName}, ${entity}> implements ${table.serviceName}{
}
5、controller.java.vm
package ${package.Controller};
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guodi.common.entity.AjaxResult;
import com.guodi.frame.system.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.guodi.common.constant.StatusCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import java.util.Date;
import ${package.Service}.${table.serviceName};
import ${package.Entity}.${entity};
/**
* @描述:$!{table.comment}控制类
* @作者: ${author}
* @日期: ${date}
*/
@RestController
@RequestMapping("/${entity}")
@Api(value = "API - ${table.controllerName}", description = "$!{table.comment}")
public class ${table.controllerName} extends BaseController {
@Autowired
public ${table.serviceName} ${table.entityPath}Service;
/**
* @描述: 根据实体属性分页查询
* @入参:
* @出参:
* @作者: ${author}
* @日期: ${date}
**/
@PostMapping("/listByEntity")
@ApiOperation(value = " 根据实体属性分页查询")
public AjaxResult listByEntity(Page page, ${entity} ${table.entityPath}){
LambdaQueryWrapper<${entity}> wrapper = new QueryWrapper().lambda();
IPage<${entity}> iPage = ${table.entityPath}Service.page(page, wrapper);
return new AjaxResult(iPage);
}
/**
* @描述: 根据主键查询
* @入参:
* @出参:
* @作者: ${author}
* @日期: ${date}
**/
@PostMapping("/findById")
@ApiOperation(value = "根据主键查询")
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "ID", required = true,
dataType = "string", paramType = "query")
})
public AjaxResult findById(String id) {
if(StringUtils.isBlank(id)){
return new AjaxResult(StatusCode.ERROR_CODE_40005,"id不能为空");
}
${entity} ${table.entityPath} = ${table.entityPath}Service.getById(id);
return new AjaxResult(${table.entityPath});
}
/**
* @描述: 新增
* @入参:
* @出参:
* @作者: ${author}
* @日期: ${date}
**/
@PostMapping("/save")
@ApiOperation(value = "新增")
public AjaxResult save(${entity} ${table.entityPath}){
prepareData(${table.entityPath}, true);
${table.entityPath}Service.save(${table.entityPath});
return new AjaxResult();
}
/**
* @描述: 修改
* @入参:
* @出参:
* @作者: ${author}
* @日期: ${date}
**/
@PostMapping("/update")
@ApiOperation(value = "修改")
public AjaxResult update(${entity} ${table.entityPath}) {
prepareData(${table.entityPath}, false);
${table.entityPath}Service.updateById(${table.entityPath});
return new AjaxResult();
}
/**
* @描述: 根据主键删除
* @入参: id
* @出参:
* @作者: ${author}
* @日期: ${date}
**/
@PostMapping("/delete")
@ApiOperation(value = "根据主键删除")
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "ID", required = true,
dataType = "string", paramType = "query")
})
public AjaxResult delete(String id){
${table.entityPath}Service.removeById(id);
return new AjaxResult();
}
private void prepareData(${entity} ${table.entityPath}, boolean isSave) {
if(isSave){
${table.entityPath}.setCreator(getCurUser().getId());
${table.entityPath}.setCreateTime(new Date());
//防止误修改
${table.entityPath}.setModifier(null);
${table.entityPath}.setModifyTime(null);
}else{
${table.entityPath}.setModifier(getCurUser().getId());
${table.entityPath}.setModifyTime(new Date());
//防止误修改
${table.entityPath}.setCreator(null);
${table.entityPath}.setCreateTime(null);
}
}
}
6、生成代码
@Test
public void generator() {
plusGenerator.generatorByType("XXX", "com.XXX","oracle", "t_test");
}