Mybatis-Plus-Generator代码生成器
1、所需依赖
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.0</version>
</dependency>
<!-- MP 代码生成器 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.2.0</version>
</dependency>
<!-- MP 代码生成默认模板(必须) -->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.7</version>
</dependency>
2、生成器
package com.womwo.demo;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
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.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
* @author robin
* @email tigerofsky@163.com
* @create 2020-11-13 15:56
*/
public class generator {
/**
* 代码生成器的配置常量
* 会生成两个mapper 删去java目录下的mapper.xml文件
* 140 行左右有解释
*/
// 生成文件包路径分类 根据模块分
private static final String MODULE_NAME = "demo";
private static final String OUT_PUT_DIR = "/src/main/java";
private static final String DATA_NAME = "root";
private static final String DATA_PWD = "root";
private static final String DATA_URL = "jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=GMT%2B8";
private static final String DRIVER_NAME = "com.mysql.cj.jdbc.Driver";
private static final String PARENT_PACKAGE = "com.womow.demo";
private static final String MAPPER_NAME = "mapper"+"."+MODULE_NAME;
private static final String SERVICE_NAME = "service"+"."+MODULE_NAME;
private static final String IMPL_NAME = "service"+"."+MODULE_NAME+".impl";
private static final String POJO_NAME = "entity"+"."+MODULE_NAME;
private static final String CONTROLLER_NAME = "controller"+"."+MODULE_NAME;
private static final String MAPPERXML = MODULE_NAME+"/";
private static final String XML_NAME = "mapper";
// 当前工程路径 配合outPutDir使用,例如多模块开发 Demo/test1,Demo/test2
// projectPath拿到的是Demo路径,把outPutDir设置成/test1即可
private static final String PROJECT_PATH = System.getProperty("user.dir");
public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = getGlobalConfig();
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = getDataSourceConfig();
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = getPackageConfig();
mpg.setPackageInfo(pc);
// 模板 自定义模板
TemplateConfig templateConfig = getTemplateConfig();
mpg.setTemplate(templateConfig);
//TemplateConfig templateConfig = new TemplateConfig();
//templateConfig.setXml(null);
mpg.setTemplate(templateConfig);
InjectionConfig cfg = getInjectionConfig();
mpg.setCfg(cfg);
// 策略配置
StrategyConfig strategy = getStrategyConfig();
mpg.setStrategy(strategy);
mpg.execute();
}
/**
* 全局配置
*
* @return
*/
public static GlobalConfig getGlobalConfig() {
return new GlobalConfig()
.setOutputDir(PROJECT_PATH + OUT_PUT_DIR)
.setDateType(DateType.ONLY_DATE)
.setAuthor("lee")
.setOpen(false)
.setBaseResultMap(true)
//如果报错 InvalidDataAcce
// ssApiUsageException则放开
//.setDateType(DateType.ONLY_DATE)
.setBaseColumnList(true)
// 覆盖生成的文件
.setFileOverride(false)
.setServiceName("%sService");
}
/**
* 数据源配置
*
* @return
*/
public static DataSourceConfig getDataSourceConfig() {
return new DataSourceConfig()
.setUrl(DATA_URL)
.setDriverName(DRIVER_NAME)
.setUsername(DATA_NAME)
.setPassword(DATA_PWD);
}
/**
* 包配置
*
* @return
*/
public static PackageConfig getPackageConfig() {
return new PackageConfig()
.setParent(PARENT_PACKAGE)
.setMapper(MAPPER_NAME)
.setEntity(POJO_NAME)
.setService(SERVICE_NAME)
.setController(CONTROLLER_NAME)
.setServiceImpl(IMPL_NAME);
}
/**
* 策略配置
*
* @return
*/
public static StrategyConfig getStrategyConfig() {
return new StrategyConfig()
.setNaming(NamingStrategy.underline_to_camel)
.setColumnNaming(NamingStrategy.underline_to_camel)
.setEntityTableFieldAnnotationEnable(true)
.setEntityLombokModel(true)
.setInclude(scanner("表名,多个英文逗号分割").split(","))
//默认生成全部
//.setExclude(null)
.setTablePrefix("表前缀_")
.setControllerMappingHyphenStyle(true)
;
}
// 配置模板 自定义模板放到vm文件夹中
public static TemplateConfig getTemplateConfig() {
TemplateConfig templateConfig = new TemplateConfig();
// 使用自定义模板,不想要生成就设置为null,如果不设置null会使用默认模板
templateConfig.setEntity("/templates/vm/entity.java.vm");
templateConfig.setController("/templates/vm/controller.java.vm");
// templateConfig.setMapper(null);
// templateConfig.setService(null);
// templateConfig.setServiceImpl(null);
templateConfig.setXml(null);
return templateConfig;
}
/**
* 自定义xml文件生成路径
* 这里注意会生成两个xml,一个是在你指定的下面,一个是在mapper包下的xml
* 暂时无法解决,因为源码中的判断,判断的是tableInfo和pathInfo的xml属性是否为null,这两个类都是默认生成属性的
* 且对if (null != injectionConfig)自定义生成的判断在默认的前面,所以会生成两遍。
* 具体可见AbstractTemplateEngine batchOutput()的方法
*
* @return
*/
public static InjectionConfig getInjectionConfig() {
// 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
}
};
String templatePath = "/templates/mapper.xml.vm";
// 自定义输出配置
List<FileOutConfig> focList = new ArrayList<>();
// 自定义配置会被优先输出
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
return PROJECT_PATH + "/src/main/resources/mapper/" + MAPPERXML + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
cfg.setFileOutConfigList(focList);
return cfg;
}
/**
* 读取控制台内容
*/
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入" + tip + ":");
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotEmpty(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("请输入正确的" + tip + "!");
}
}
3、模板
package ${package.Controller};
import org.springframework.beans.factory.annotation.Autowired;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import com.womow.zyzd.common.model.Result;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import ${package.Service}.${table.serviceName};
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
/**
* <pre>
* $!{table.comment} controller
* </pre>
*
* @author ${author}
* @date ${date}
*/
@RestController
@RequestMapping("/")
@Api(value="/", tags="${table.comment}")
public class ${table.controllerName} {
@Autowired
private ${table.serviceName} service;
/**
* 查询XXX列表
*/
@ApiOperation(value = "查询XXX列表")
@PostMapping("/")
public Result getCqgzList(@RequestBody Map<String,Object> map){
Result result = new Result();
return result;
}
}
package ${package.Entity};
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableField;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import com.baomidou.mybatisplus.annotation.TableName;
/**
* <pre>
* $!{table.comment}
* </pre>
*
* @author ${author}
* @date ${date}
*/
@Data
@TableName("${table.name}")
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" != "")
/**
* ${field.comment}
*/
#end
#if(${field.keyFlag})
## 主键
#if(${field.keyIdentityFlag})
@TableId(type= IdType.AUTO)
#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})
@TableField("${field.name}")
#end
@ApiModelProperty(name = "$field.comment", value = "$field.propertyName", required = false)
private ${field.propertyType} ${field.propertyName};
#end
## ---------- END 字段循环遍历 ----------
}