使用MyBatis-Plus-Generator代码生成工具
引入Pom依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.4.1</version>
</dependency>
<!--模板解析 -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.28</version>
</dependency>
代码生成类
package com.sgm.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.FreemarkerTemplateEngine;
import lombok.extern.slf4j.Slf4j;
import java.util.ArrayList;
import java.util.List;
@Slf4j
public class CodeGenerator {
//多个表,分割
static String tableNames = "PGMS_Admin";
//代码生成的项目
static String proPath = "/common";
//代码生成的路径
static String dataPath = "/src/main/java";
//项目生成包名
static String packageName = "com.sgm";
//代码生成作者
static String author = "zzw";
//数据库连接
static String dbUrl = "jdbc:sqlserver://127.0.0.1:1433;databaseName=PGSP;encrypt=true;trustServerCertificate=true";
//数据库驱动
static String dbDrive = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
//数据库用户名
static String dbUser = "sa";
//数据库密码
static String dbPwd = "123456";
/**
* RUN THIS
*/
public static void main(String[] args) {
//获取控制台的数据
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
String path = System.getProperty("user.dir");
String projectPath = path ;//+ proPath;
gc.setOutputDir(projectPath + dataPath); //生成文件的输出目录
log.info("文件生成路径:{}", projectPath + dataPath);
gc.setAuthor(author); //作者
gc.setFileOverride(true); //是否覆蓋已有文件 默认值:false
gc.setOpen(false); //是否打开输出目录 默认值:true
gc.setBaseColumnList(true); //开启 baseColumnList 默认false
gc.setBaseResultMap(true); //开启 BaseResultMap 默认false
gc.setMapperName("%sMapper"); //mapper 命名方式 默认值:null 例如:%sDao 生成 UserDao
gc.setXmlName("%sMapper"); //Mapper xml 命名方式 默认值:null 例如:%sDao 生成 UserDao.xml
gc.setServiceName("%sService"); //service 命名方式 默认值:null 例如:%sBusiness 生成 UserBusiness
gc.setServiceImplName("%sServiceImpl"); //service impl 命名方式 默认值:null 例如:%sBusinessImpl 生成 UserBusinessImpl
gc.setControllerName("%sController"); //controller 命名方式 默认值:null 例如:%sAction 生成 UserAction
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl(dbUrl);
dsc.setDriverName(dbDrive);
dsc.setUsername(dbUser);
dsc.setPassword(dbPwd);
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setParent(packageName);
pc.setModuleName(null);
pc.setMapper("mapper");
pc.setEntity("entity");
pc.setService("service");
pc.setServiceImpl("service.impl");
pc.setController("controller");
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
mpg.setPackageInfo(pc);
List<FileOutConfig> focList = new ArrayList<>();
focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输入文件名称
return projectPath + "/src/main/resources/mapper/" +
tableInfo.getEntityName() + "Mapper" +
StringPool.DOT_XML;
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
mpg.setTemplate(new TemplateConfig().setXml(null));
// 策略配置 数据库表配置,通过该配置,可指定需要生成哪些表或者排除哪些表
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel); //表名生成策略
strategy.setColumnNaming(NamingStrategy.underline_to_camel);//数据库表字段映射到实体的命名策略, 未指定按照 naming 执行
strategy.setEntityLombokModel(true); //【实体】是否为lombok模型(默认 false
strategy.setRestControllerStyle(true); //生成 @RestController 控制器
String tables = tableNames;
String[] num = tables.split(",");
log.info("生产表数量:{}, 表:{}", num.length, tables);
strategy.setInclude(num); // 需要生成的表可以多张表
//strategy.setExclude(new String[]{"test"}); // 排除生成的表
//strategy.setTablePrefix("bus_");
//strategy.setTablePrefix("sys_");
strategy.setControllerMappingHyphenStyle(true); //驼峰转连字符
strategy.setTablePrefix(pc.getModuleName() + "_"); //是否生成实体时,生成字段注解
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
}
写生成代码的模板
模板命名方式 controller.java.ftl、entity.java.ftl、mapper.java.ftl、mapper.xml.ftl、service.java.ftl、serviceimpl.java.ftl
存放路径 resource/templates
//Controller模板
package ${package.Controller};
import ${package.Entity}.${entity};
import ${package.Mapper}.${table.mapperName};
import ${package.Service}.${table.serviceName};
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.apache.ibatis.annotations.Param;
import java.util.List;
@RestController
@Api(tags = "/${table.name}")
public class ${table.controllerName} {
@Autowired
private ${table.serviceName} ${table.entityPath}Service;
<#list table.fields as field>
<#if field.keyFlag>
/**
* 根据主键${field.propertyName}查询表${table.name}信息
* @param ${field.propertyName}
*/
@PostMapping("/find${entity}By${field.propertyName}")
public ${entity} find${entity}By${field.propertyName}(@Param("${field.propertyName}") ${field.propertyType} ${field.propertyName}) {
return ${table.entityPath}Service.find${entity}By${field.propertyName}(${field.propertyName});
}
</#if>
</#list>
/**
* 根据条件查询表${table.name}信息
* @param ${table.entityPath}
*/
@PostMapping("/find${entity}ByCondition(${entity} ${table.entityPath}")
public List<${entity}> find${entity}ByCondition(${entity} ${table.entityPath}) {
return ${table.entityPath}Service.find${entity}ByCondition(${table.entityPath});
}
<#list table.fields as field>
<#if field.keyFlag>
/**
* 根据主键${field.propertyName}查询表${table.name}信息
* @param ${field.propertyName}
*/
@PostMapping("/delete${entity}By${field.propertyName}")
public Integer delete${entity}By${field.propertyName}(@Param("${field.propertyName}") ${field.propertyType} ${field.propertyName}) {
return ${table.entityPath}Service.delete${entity}By${field.propertyName}(${field.propertyName});
}
</#if>
</#list>
<#list table.fields as field>
<#if field.keyFlag>
/**
* 根据主键${field.propertyName}更新表${table.name}信息
* @param ${table.entityPath}
*/
@PostMapping("/update${entity}By${field.propertyName}")
public Integer update${entity}By${field.propertyName}(${entity} ${table.entityPath}) {
return ${table.entityPath}Service.update${entity}By${field.propertyName}(${table.entityPath});
}
</#if>
</#list>
<#list table.fields as field>
<#if field.keyFlag>
/**
* 新增表${table.name}信息
* @param ${table.entityPath}
*/
@PostMapping("/add${entity}(${entity}")
public Integer add${entity}(${entity} ${table.entityPath}) {
return ${table.entityPath}Service.add${entity}(${table.entityPath});
}
</#if>
</#list>
}
//entity模板
//entity模板
//entity模板
package ${package.Entity};
import java.io.Serializable;
import java.util.Date;
import lombok.Data;
import lombok.EqualsAndHashCode;
<#list table.importPackages as pkg>
<#if pkg == "java.util.Date">
import ${pkg};
</#if>
</#list>
/**
* ${table.name} : ${table.comment!}
*/
@Data
@EqualsAndHashCode(callSuper = false)
public class ${entity} implements Serializable {
private static final long serialVersionUID = 1L;
<#-- ---------- 属性私有化 ---------->
<#list table.fields as field>
<#if field.keyFlag>
<#assign keyPropertyName="${field.propertyName}"/>
</#if>
<#if field.keyFlag>
<#-- 主键 -->
/**
* 主键 : ${field.name}, ${field.comment!}
*/
<#-- 普通字段 -->
<#elseif !field.keyFlag>
/**
* ${field.name}, ${field.comment!}
*/
</#if>
<#-- 乐观锁注解 -->
<#if (versionFieldName!"") == field.name>
@Version
</#if>
<#-- 逻辑删除注解 -->
<#if (logicDeleteFieldName!"") == field.name>
@TableLogic
</#if>
<#if field.propertyType == "LocalDateTime">
private Date ${field.propertyName};
</#if>
<#if field.propertyType != "LocalDateTime">
private ${field.propertyType} ${field.propertyName};
</#if>
</#list>
<#--<#–---------- 构造函数 ----------- –>-->
<#--public ${entity}(<#list table.fields as field><#if field.propertyType == "LocalDateTime">Date ${field.propertyName}</#if><#if field.propertyType != "LocalDateTime">${field.propertyType} ${field.propertyName}</#if><#sep>,</#list>){-->
<#--<#list table.fields as field>-->
<#-- this.${field.propertyName} = ${field.propertyName};-->
<#--</#list>-->
<#--}-->
<#--public ${entity}(){-->
<#--}-->
<#------------ getter.setter封装 ---------->
<#--<#if !entityLombokModel>-->
<#-- <#list table.fields as field>-->
<#-- <#if field.propertyType == "boolean">-->
<#-- <#assign getprefix="is"/>-->
<#-- <#else>-->
<#-- <#assign getprefix="get"/>-->
<#-- </#if>-->
<#-- public <#if field.propertyType == "LocalDateTime">Date</#if><#if field.propertyType != "LocalDateTime">${field.propertyType}</#if> ${getprefix}${field.capitalName}() {-->
<#-- return ${field.propertyName};-->
<#-- }-->
<#-- <#if entityBuilderModel>-->
<#-- public ${entity} set${field.capitalName}(${field.propertyType} ${field.propertyName}) {-->
<#-- <#else>-->
<#-- public void set${field.capitalName}(<#if field.propertyType == "LocalDateTime">Date</#if><#if field.propertyType != "LocalDateTime">${field.propertyType}</#if> ${field.propertyName}) {-->
<#-- </#if>-->
<#-- this.${field.propertyName} = ${field.propertyName};-->
<#-- <#if entityBuilderModel>-->
<#-- return this;-->
<#-- </#if>-->
<#-- }-->
<#-- </#list>-->
<#--</#if>-->
<#------------- 重写toString() ----------------->
<#--<#if !entityLombokModel>-->
<#-- @Override-->
<#-- public String toString() {-->
<#-- return "${entity}{" +-->
<#-- <#list table.fields as field>-->
<#-- <#if field_index==0>-->
<#-- "${field.propertyName}=" + ${field.propertyName} +-->
<#-- <#else>-->
<#-- ", ${field.propertyName}=" + ${field.propertyName} +-->
<#-- </#if>-->
<#-- </#list>-->
<#-- "}";-->
<#-- }-->
<#--</#if>-->
}
//mapper模板
//mapper模板
//mapper模板
package ${package.Mapper};
import ${package.Entity}.${entity};
import java.util.List;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface ${table.mapperName}{
/**
* 查询表${table.name}所有信息
*/
List<${entity}> findAll${entity}();
<#list table.fields as field>
<#if field.keyFlag>
/**
* 根据主键${field.propertyName}查询表${table.name}信息
* @param ${field.propertyName}
*/
${entity} find${entity}By${field.propertyName}(@Param("${field.propertyName}") ${field.propertyType} ${field.propertyName});
</#if>
</#list>
/**
* 根据条件查询表${table.name}信息
* @param ${table.entityPath}
*/
List<${entity}> find${entity}ByCondition(${entity} ${table.entityPath});
<#list table.fields as field>
<#if field.keyFlag>
/**
* 根据主键${field.propertyName}查询表${table.name}信息
* @param ${field.propertyName}
*/
Integer delete${entity}By${field.propertyName}(@Param("${field.propertyName}") ${field.propertyType} ${field.propertyName});
</#if>
</#list>
<#list table.fields as field>
<#if field.keyFlag>
/**
* 根据主键${field.propertyName}更新表${table.name}信息
* @param ${table.entityPath}
*/
Integer update${entity}By${field.propertyName}(${entity} ${table.entityPath});
</#if>
</#list>
<#list table.fields as field>
<#if field.keyFlag>
/**
* 新增表${table.name}信息
* @param ${table.entityPath}
*/
Integer add${entity}(${entity} ${table.entityPath});
</#if>
</#list>
}
//mapper.xml模板
<?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 baseColumnList>
<!-- 通用查询列 -->
<sql id="Base_Column_List">
<#list table.commonFields as field>
${field.name},
</#list>
${table.fieldNames}
</sql>
<!-- 通用条件列 -->
<sql id="${entity}ByCondition">
<#list table.commonFields as field><#--生成公共字段-->
<if test="${field.propertyName}!=null and ${field.propertyName}!=''">
AND ${field.name} = ${r"#{"}${field.propertyName}${r"}"}
</if>
</#list>
<#list table.fields as field>
<#if !field.keyFlag><#--生成普通字段 -->
<if test="${field.propertyName}!=null and ${field.propertyName}!=''">
AND ${field.name} = ${r"#{"}${field.propertyName}${r"}"}
</if>
</#if>
</#list>
</sql>
<!-- 通用设置列 -->
<sql id="${entity}SetColumns">
<#list table.commonFields as field><#--生成公共字段-->
<if test="${field.propertyName}!=null and ${field.propertyName}!=''">
${field.name} = ${r"#{"}${field.propertyName}${r"}"},
</if>
</#list>
<#list table.fields as field>
<#if !field.keyFlag><#--生成普通字段 -->
<if test="${field.propertyName}!=null and ${field.propertyName}!=''">
${field.name} = ${r"#{"}${field.propertyName}${r"}"},
</if>
</#if>
</#list>
</sql>
</#if>
<#if baseResultMap>
<!-- 通用查询映射结果 -->
<resultMap id="${entity}Map" type="${package.Entity}.${entity}">
<#list table.fields as field>
<#if field.keyFlag><#--生成主键排在第一位-->
<id column="${field.name}" property="${field.propertyName}"/>
</#if>
</#list>
<#list table.commonFields as field><#--生成公共字段 -->
<result column="${field.name}" property="${field.propertyName}"/>
</#list>
<#list table.fields as field>
<#if !field.keyFlag><#--生成普通字段 -->
<result column="${field.name}" property="${field.propertyName}"/>
</#if>
</#list>
</resultMap>
</#if>
<!-- 查询表${table.name}所有信息 -->
<select id="findAll${entity}" resultMap="${entity}Map">
SELECT
<include refid="Base_Column_List"/>
FROM ${table.name}
</select>
<#list table.fields as field>
<#if field.keyFlag>
<!-- 根据主键${field.propertyName}查询表${table.name}信息 -->
<select id="find${entity}By${field.propertyName}" resultMap="${entity}Map">
SELECT
<include refid="Base_Column_List"/>
FROM ${table.name}
WHERE ${field.name}=${r"#{"}${field.propertyName}${r"}"}
</select>
</#if>
</#list>
<!-- 根据条件查询表${table.name}信息 -->
<select id="find${entity}ByCondition" resultMap="${entity}Map">
SELECT
<include refid="Base_Column_List"/>
FROM ${table.name}
WHERE 1=1
<include refid="${entity}ByCondition" />
</select>
<#list table.fields as field>
<#if field.keyFlag>
<!-- 根据主键${field.propertyName}删除表${table.name}信息 -->
<delete id="delete${entity}By${field.propertyName}">
DELETE FROM
${table.name}
WHERE ${field.name}=${r"#{"}${field.propertyName}${r"}"}
</delete>
</#if>
</#list>
<#list table.fields as field>
<#if field.keyFlag>
<!-- 根据主键${field.propertyName}更新表${table.name}信息 -->
<update id="update${entity}By${field.propertyName}" parameterType="${package.Entity}.${entity}">
UPDATE ${table.name}
<set>
<include refid="${entity}SetColumns"/>
</set>
WHERE
<#list table.fields as field><#if field.keyFlag>${field.name}=${r"#{"}${field.propertyName}${r"}"}</#if></#list>
</update>
</#if>
</#list>
<#list table.fields as field>
<#if field.keyFlag>
<!-- 新增表${table.name}信息 -->
<insert id="add${entity}">
INSERT INTO ${table.name} (
<#list table.fields as field>
<#if field_index gt 0>,</#if>${field.name}
</#list>
) VALUES (
<#list table.fields as field>
<#if field_index gt 0>,</#if>${r"#{"}${field.propertyName}${r"}"}
</#list>
)
</insert>
</#if>
</#list>
</mapper>
//service模板
//service模板
//service模板
package ${package.Service};
import ${package.Entity}.${entity};
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface ${table.serviceName}{
/**
* 查询表${table.name}所有信息
*/
List<${entity}> findAll${entity}();
<#list table.fields as field>
<#if field.keyFlag>
/**
* 根据主键${field.propertyName}查询表${table.name}信息
* @param ${field.propertyName}
*/
${entity} find${entity}By${field.propertyName}(@Param("${field.propertyName}") ${field.propertyType} ${field.propertyName});
</#if>
</#list>
/**
* 根据条件查询表${table.name}信息
* @param ${table.entityPath}
*/
List<${entity}> find${entity}ByCondition(${entity} ${table.entityPath});
<#list table.fields as field>
<#if field.keyFlag>
/**
* 根据主键${field.propertyName}查询表${table.name}信息
* @param ${field.propertyName}
*/
Integer delete${entity}By${field.propertyName}(@Param("${field.propertyName}") ${field.propertyType} ${field.propertyName});
</#if>
</#list>
<#list table.fields as field>
<#if field.keyFlag>
/**
* 根据主键${field.propertyName}更新表${table.name}信息
* @param ${table.entityPath}
*/
Integer update${entity}By${field.propertyName}(${entity} ${table.entityPath});
</#if>
</#list>
<#list table.fields as field>
<#if field.keyFlag>
/**
* 新增表${table.name}信息
* @param ${table.entityPath}
*/
Integer add${entity}(${entity} ${table.entityPath});
</#if>
</#list>
}
//serviceImpl模板
package ${package.ServiceImpl};
import ${package.Entity}.${entity};
import ${package.Mapper}.${table.mapperName};
import ${package.Service}.${table.serviceName};
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.apache.ibatis.annotations.Param;
import java.util.List;
@Service
public class ${table.serviceImplName} implements ${table.serviceName} {
@Autowired
private ${table.mapperName} ${table.entityPath}Mapper;
/**
* 查询表${table.name}所有信息
*/
@Override
public List<${entity}> findAll${entity}() { return ${table.entityPath}Mapper.findAll${entity}();}
<#list table.fields as field>
<#if field.keyFlag>
/**
* 根据主键${field.propertyName}查询表${table.name}信息
* @param ${field.propertyName}
*/
@Override
public ${entity} find${entity}By${field.propertyName}(@Param("${field.propertyName}") ${field.propertyType} ${field.propertyName}) { return ${table.entityPath}Mapper.find${entity}By${field.propertyName}(${field.propertyName});}
</#if>
</#list>
/**
* 根据条件查询表${table.name}信息
* @param ${table.entityPath}
*/
@Override
public List<${entity}> find${entity}ByCondition(${entity} ${table.entityPath}) { return ${table.entityPath}Mapper.find${entity}ByCondition(${table.entityPath});}
<#list table.fields as field>
<#if field.keyFlag>
/**
* 根据主键${field.propertyName}查询表${table.name}信息
* @param ${field.propertyName}
*/
@Override
public Integer delete${entity}By${field.propertyName}(@Param("${field.propertyName}") ${field.propertyType} ${field.propertyName}) { return ${table.entityPath}Mapper.delete${entity}By${field.propertyName}(${field.propertyName});}
</#if>
</#list>
<#list table.fields as field>
<#if field.keyFlag>
/**
* 根据主键${field.propertyName}更新表${table.name}信息
* @param ${table.entityPath}
*/
@Override
public Integer update${entity}By${field.propertyName}(${entity} ${table.entityPath}) { return ${table.entityPath}Mapper.update${entity}By${field.propertyName}(${table.entityPath});}
</#if>
</#list>
<#list table.fields as field>
<#if field.keyFlag>
/**
* 新增表${table.name}信息
* @param ${table.entityPath}
*/
@Override
public Integer add${entity}(${entity} ${table.entityPath}) { return ${table.entityPath}Mapper.add${entity}(${table.entityPath});}
</#if>
</#list>
}