最近闲来无事整理了一下 mybatisplus-generator 代码生成器,话不多少说先上效果图
引入、mybatis-springboot,mybatis-plus等包,下面是我自己的pom 工程文件
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>com.mybatis_plus.generatorgroupId>
<artifactId>plus_generatorartifactId>
<version>1.0-SNAPSHOTversion>
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>2.2.6.RELEASEversion>
<relativePath/>
parent>
<properties>
<java.version>1.8java.version>
<mybatis.version>2.1.2mybatis.version>
<druid.version>1.1.6druid.version>
<jwt.version>1.0.9.RELEASEjwt.version>
<jjwt.version>0.9.0jjwt.version>
<fastJson.version>1.2.45fastJson.version>
<mybatisPlus.version>3.3.1mybatisPlus.version>
<common.version>3.5common.version>
<swagger.version>2.8.0swagger.version>
properties>
<dependencies>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-data-redisartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-securityartifactId>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.mybatis.spring.bootgroupId>
<artifactId>mybatis-spring-boot-starterartifactId>
<version>${mybatis.version}version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>${druid.version}version>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-devtoolsartifactId>
<scope>runtimescope>
<optional>trueoptional>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<scope>runtimescope>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<optional>trueoptional>
dependency>
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-testartifactId>
<scope>testscope>
<exclusions>
<exclusion>
<groupId>org.junit.vintagegroupId>
<artifactId>junit-vintage-engineartifactId>
exclusion>
exclusions>
dependency>
<dependency>
<groupId>org.springframework.securitygroupId>
<artifactId>spring-security-testartifactId>
<scope>testscope>
dependency>
<dependency>
<groupId>org.springframework.securitygroupId>
<artifactId>spring-security-jwtartifactId>
<version>${jwt.version}version>
dependency>
<dependency>
<groupId>io.jsonwebtokengroupId>
<artifactId>jjwtartifactId>
<version>${jjwt.version}version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>${fastJson.version}version>
dependency>
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-boot-starterartifactId>
<version>${mybatisPlus.version}version>
dependency>
<dependency>
<groupId>org.apache.commonsgroupId>
<artifactId>commons-lang3artifactId>
<version>${common.version}version>
dependency>
<dependency>
<groupId>io.springfoxgroupId>
<artifactId>springfox-swagger2artifactId>
<version>${swagger.version}version>
dependency>
<dependency>
<groupId>io.springfoxgroupId>
<artifactId>springfox-swagger-uiartifactId>
<version>${swagger.version}version>
dependency>
<dependency>
<groupId>commons-netgroupId>
<artifactId>commons-netartifactId>
<version>3.6version>
dependency>
<dependency>
<groupId>cn.hutoolgroupId>
<artifactId>hutool-allartifactId>
<version>4.1.19version>
dependency>
<dependency>
<groupId>org.apache.poigroupId>
<artifactId>poi-ooxmlartifactId>
<version>4.0.0version>
dependency>
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-generatorartifactId>
<version>3.2.0version>
dependency>
<dependency>
<groupId>org.apache.velocitygroupId>
<artifactId>velocity-engine-coreartifactId>
<version>2.2version>
dependency>
dependencies>
project>
在resources包下创建 generator文件夹将 controller.java.vm、service.java.vm、serviceImpl.java.vm、mapper.java.vm、mapper.xml.vm、entity.java.vm 放进去(效果图)
package ${
package.Controller};
import org.springframework.web.bind.annotation.RequestMapping;
import ${
package.Service}.${
table.serviceName};
#if(${
restControllerStyle})
import org.springframework.web.bind.annotation.RestController;
#else
import org.springframework.stereotype.Controller;
#end
#if(${
superControllerClassPackage})
import ${
superControllerClassPackage};
#end
/**
* @Author: ${author}
* @Date: ${cfg.dateTime}
* @Description: $!{table.comment}
*/
#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
public final ${
table.serviceName} service;
public ${
table.controllerName}(${
table.serviceName} service) {
this.service = service;
}
}
#end
package ${
package.Service};
import ${
package.Entity}.${
entity};
import ${
superServiceClassPackage};
/**
* @Author: ${author}
* @Date: ${cfg.dateTime}
* @Description: $!{table.comment}服务类
*/
#if(${
kotlin})
interface ${
table.serviceName} : ${
superServiceClass}<${
entity}>
#else
public interface ${
table.serviceName} extends ${
superServiceClass}<${
entity}> {
}
#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;
/**
* @Author: ${author}
* @Date: ${cfg.dateTime}
* @Description: $!{table.comment}服务实现类
*/
@Service
@Transactional(rollbackFor = Exception.class)
#if(${
kotlin})
open class ${
table.serviceImplName} : ${
superServiceImplClass}<${
table.mapperName}, ${
entity}Model>(), ${
table.serviceName} {
}
#else
public class ${
table.serviceImplName} extends ${
superServiceImplClass}<${
table.mapperName}, ${
entity}> implements ${
table.serviceName} {
}
#end
package ${
package.Mapper};
import ${
package.Entity}.${
entity};
import ${
superMapperClassPackage};
/**
* @Author: ${author}
* @Date: ${cfg.dateTime}
* @Description: $!{table.comment}Mapper
*/
#if(${
kotlin})
interface ${
table.mapperName} : ${
superMapperClass}<${
entity}>
#else
public interface ${
table.mapperName} extends ${
superMapperClass}<${
entity}> {
}
#end
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="${package.Mapper}.${table.mapperName}">
#if(${
enableCache})
<!-- 开启二级缓存 -->
<cache type="org.mybatis.caches.ehcache.LoggingEhcache"/>
#end
#if(${
baseResultMap})
<!-- 通用查询映射结果 -->
<resultMap id="BaseResultMap" type="${package.Entity}.${entity}">
#foreach($field in ${
table.fields})
#if(${
field.keyFlag})##生成主键排在第一位
<id column="${field.name}" property="${field.propertyName}" />
#end
#end
#foreach($field in ${
table.commonFields})##生成公共字段
<result column="${field.name}" property="${field.propertyName}" />
#end
#foreach($field in ${
table.fields})
#if(!${
field.keyFlag})##生成普通字段
<result column="${field.name}" property="${field.propertyName}" />
#end
#end
</resultMap>
#end
#if(${
baseColumnList})
<!-- 通用查询结果列 -->
<sql id="Base_Column_List">
#foreach($field in ${
table.commonFields})
${
field.name},
#end
${
table.fieldNames}
</sql>
#end
</mapper>
package ${
package.Entity};
#foreach($pkg in ${
table.importPackages})
import ${
pkg};
#end
import com.baomidou.mybatisplus.annotation.*;
#if(${
swagger2})
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import com.fasterxml.jackson.annotation.JsonInclude;
#end
#if(${
entityLombokModel})
import lombok.Data;
import lombok.experimental.Accessors;
#end
/**
* @Author: ${author}
* @Date: ${cfg.dateTime}
* @Description: $!{table.comment}
*/
#if(${
entityLombokModel})
@Data
#end
@TableName("${table.name}")
#if(${
swagger2})
@JsonInclude(JsonInclude.Include.NON_NULL)
@Accessors(chain = true)
@ApiModel(value="${entity}对象", description="$!{table.comment}")
#end
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" != "")
#if(${
swagger2})
@ApiModelProperty(value = "${field.comment}")
#else
/**
* ${field.comment}
*/
#end
#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
#else
@TableField("${field.name}")
#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}Model{" +
#foreach($field in ${
table.fields})
#if($!{
foreach.index}==0)
"${field.propertyName}=" + ${
field.propertyName} +
#else
", ${field.propertyName}=" + ${
field.propertyName} +
#end
#end
"}";
}
#end
}
package com.mybatisplus.generator;
import com.baomidou.mybatisplus.annotation.IdType;
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 com.sun.javafx.PlatformUtil;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
/**
* @author River
*/
public class CodeGenerator {
/**
* 代码生成位置
*/
public static final String PARENT_NAME = "com.mybatisplus.generator";
/**
* modular 名字
*/
public static final String MODULAR_NAME = "";
/**
* 基本路径
*/
public static final String SRC_MAIN_JAVA = "src/main/java/";
/**
* 作者
*/
public static final String AUTHOR = "LiuRunYong";
/**
* 是否是 rest 接口
*/
private static final boolean REST_CONTROLLER_STYLE = true;
public static final String JDBC_MYSQL_URL = "jdbc:mysql://ip:port/database?characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai";
public static final String JDBC_DRIVER_NAME = "com.mysql.cj.jdbc.Driver";
public static final String JDBC_USERNAME = "user";
public static final String JDBC_PASSWORD = "user234";
public static void main(String[] args) {
String moduleName = scanner("模块名");
String tableName = scanner("表名(多个表明用,号隔开)");
String tablePrefix = scanner("表前缀(无前缀输入#)").replaceAll("#", "");
autoGenerator(moduleName, tableName, tablePrefix);
}
public static void autoGenerator(String moduleName, String tableName, String tablePrefix) {
new AutoGenerator()
.setGlobalConfig(getGlobalConfig())
.setDataSource(getDataSourceConfig())
.setPackageInfo(getPackageConfig(moduleName))
.setStrategy(getStrategyConfig(tableName, tablePrefix))
.setCfg(getInjectionConfig(moduleName))
.setTemplate(getTemplateConfig())
.execute();
}
private static String getDateTime() {
LocalDateTime localDate = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
return localDate.format(formatter);
}
private static InjectionConfig getInjectionConfig(final String moduleName) {
return new InjectionConfig() {
@Override
public void initMap() {
Map<String,Object> map = new HashMap<>(10);
map.put("dateTime", getDateTime());
setMap(map);
final String projectPath = System.getProperty("user.dir");
List<FileOutConfig> fileOutConfigList = new ArrayList<FileOutConfig>();
// 自定义配置会被优先输出
fileOutConfigList.add(new FileOutConfig("/generator/mapper.xml.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名,如果entity设置了前后缀,此次注意xml的名称也会跟着发生变化
return projectPath + "/src/main/resources/mapper/" +
moduleName + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
setFileOutConfigList(fileOutConfigList);
}
};
}
private static StrategyConfig getStrategyConfig(String tableName, String tablePrefix) {
return new StrategyConfig()
.setNaming(NamingStrategy.underline_to_camel)
.setColumnNaming(NamingStrategy.underline_to_camel)
.setInclude(tableName.split(","))
.setRestControllerStyle(REST_CONTROLLER_STYLE)
.setEntityBuilderModel(true)
.setControllerMappingHyphenStyle(true)
.entityTableFieldAnnotationEnable(true)
.setEntityLombokModel(true)
.setTablePrefix(tablePrefix + "_");
}
private static PackageConfig getPackageConfig(String moduleName) {
return new PackageConfig()
.setModuleName(moduleName)
.setParent(PARENT_NAME)
.setService("service")
.setServiceImpl("serviceimpl")
.setController("controller")
.setEntity("model");
}
private static DataSourceConfig getDataSourceConfig() {
return new DataSourceConfig()
.setUrl(JDBC_MYSQL_URL)
.setDriverName(JDBC_DRIVER_NAME)
.setUsername(JDBC_USERNAME)
.setPassword(JDBC_PASSWORD);
}
private static GlobalConfig getGlobalConfig() {
String projectPath = System.getProperty("user.dir");
String filePath = projectPath + "/" + MODULAR_NAME + SRC_MAIN_JAVA;
if (PlatformUtil.isWindows()) {
filePath = filePath.replaceAll("/+|\\\\+", "\\\\");
} else {
filePath = filePath.replaceAll("/+|\\\\+", "/");
}
return new GlobalConfig()
.setOutputDir(filePath)
.setDateType(DateType.ONLY_DATE)
.setIdType(IdType.UUID)
.setAuthor(AUTHOR)
.setBaseColumnList(true)
.setSwagger2(true)
.setEnableCache(false)
.setBaseResultMap(true)
.setMapperName("%sMapper")
//.setXmlName("%sMapper")
.setServiceName("%sService")
.setServiceImplName("%sServiceImpl")
.setControllerName("%sController")
.setEntityName("%sModel")
.setOpen(false);
}
private static TemplateConfig getTemplateConfig() {
return new TemplateConfig()
.setController("/generator/controller.java.vm")
.setService("/generator/service.java.vm")
.setServiceImpl("/generator/serviceImpl.java.vm")
.setEntity("/generator/entity.java.vm")
.setMapper("/generator/mapper.java.vm")
.setXml(null);
}
private static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder sb = new StringBuilder();
sb.append("please input " + tip + " : ");
System.out.println(sb.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotEmpty(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("please input the correct " + tip + ". ");
}
}