1、创建表sys_units_dict
2、pom文件配置
<!--mybatisPlus插件-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.2</version>
</dependency>
<!--代码生成器-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.3.2</version>
</dependency>
<!-- 扩展代码生成插件 zhuwh -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.30</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.8</version>
</dependency>
<!--geoTools外围jar-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
3、新建生成器类(CodeGeneratorUtils)
package com.gsgx.project.tool.generator;
/**
* @Author: FanJiaKai
* @Description:
* @Date: Created in 2021/7/13 21:53
*/
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
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.builder.ConfigBuilder;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.FileType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import org.apache.commons.lang3.StringUtils;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
* @Desc: MyBatisPlus代码生成器
* @Author: Administrator
* @Date: 2020/11/2320:32
*/
@SuppressWarnings("all")
public class CodeGeneratorUtils {
/**
* 读取控制台内容
*/
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("请输入" + tip + ":");
System.out.println(help.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotEmpty(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("请输入正确的" + tip + "!");
}
public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/src/main/java");
// gc.setOutputDir("D:\\test");
gc.setAuthor("kk");
//是否打开输出目录
gc.setOpen(false);
//是否覆盖已有文件
gc.setFileOverride(true);
gc.setBaseColumnList(true);
gc.setBaseResultMap(true);
gc.setSwagger2(true); // 实体属性 Swagger2 注解
//service 命名方式
gc.setServiceName("%sService");
//entity 命名方式
gc.setEntityName("%sEntity");
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:postgresql://114.116.236.4:5432/traffic_survey_db");
dsc.setDriverName("org.postgresql.Driver");
dsc.setUsername("postgres");
dsc.setPassword("Aolutong123!@#");
dsc.setSchemaName("public");
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName(null);
pc.setParent("com.gsgx.project.demo");
pc.setEntity("model.entity");
pc.setMapper("dao");
// pc.setXml("mybatis.survey");
mpg.setPackageInfo(pc);
// 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
cfg.setFileCreate(new IFileCreate() {
@Override
public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
//如果不存在,创建;如果存在,判断是否是entity.java:如果是,创建(覆盖);否则,不创建。
checkDir(filePath);
File file = new File(filePath);
boolean exist = file.exists();
if (exist) {
/*if (FileType.ENTITY == fileType) {
return false;
} else if (FileType.OTHER == fileType) {
return true;
} else {
return false;
}*/
}
return true;
}
});
// 如果模板引擎是 freemarker
String mapperPath = "/templates/mapper.xml.ftl";
String reqPath = "/templates/req.java.ftl";
String saveReqPath = "/templates/saveReq.java.ftl";
String viewPath = "/templates/view.java.ftl";
// 如果模板引擎是 velocity
// String templatePath = "/templates/mapper.xml.vm";
// 自定义输出配置
List<FileOutConfig> focList = new ArrayList<>();
// 自定义配置会被优先输出
focList.add(new FileOutConfig(mapperPath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
return projectPath + "/src/main/resources/mybatis/demo/" + tableInfo.getEntityName().replace("Entity","") + "Mapper" + StringPool.DOT_XML;
}
});
focList.add(new FileOutConfig(reqPath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
return projectPath + "/src/main/java/com/gsgx/project/demo/model/req/" + tableInfo.getEntityName().replace("Entity","") + "Req" + StringPool.DOT_JAVA;
}
});
focList.add(new FileOutConfig(saveReqPath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
return projectPath + "/src/main/java/com/gsgx/project/demo/model/req/" + tableInfo.getEntityName().replace("Entity","") + "SaveReq" + StringPool.DOT_JAVA;
}
});
focList.add(new FileOutConfig(viewPath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
return projectPath + "/src/main/java/com/gsgx/project/demo/model/view/" + tableInfo.getEntityName().replace("Entity","") + "View" + StringPool.DOT_JAVA;
}
});
/*focList.add(new FileOutConfig(entityPath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
return projectPath + "/src/main/java/com/gsgx/project/demo/model/entity/" + tableInfo.getEntityName() + StringPool.DOT_JAVA;
}
});*/
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
// 配置自定义输出模板
//指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
templateConfig.setEntity("templates/entity.java");
templateConfig.setMapper("templates/mapper.java");
templateConfig.setController("templates/controller.java");
// templateConfig.setService();
// templateConfig.setController();
templateConfig.setService("templates/service.java");
templateConfig.setServiceImpl("templates/serviceImpl.java");
templateConfig.setXml(null);
mpg.setTemplate(templateConfig);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
//数据库表映射到实体的命名策略
strategy.setNaming(NamingStrategy.underline_to_camel);
//数据库表字段映射到实体的命名策略, 未指定按照 naming 执行
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
//字段前缀
strategy.setFieldPrefix("R_","T_","D_","I_","N_");
strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
//驼峰转连字符
strategy.setControllerMappingHyphenStyle(true);
// strategy.setTablePrefix(pc.getModuleName() + "_");
//tablePrefix
strategy.setTablePrefix("survey" + "_");
//Boolean类型字段是否移除is前缀
strategy.setEntityBooleanColumnRemoveIsPrefix(true);
//逻辑删除属性名称
strategy.setLogicDeleteFieldName("del");
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
}
4、配置模板
controller.java.ftl
package ${package.Controller};
import com.traffic.common.response.ResponseJson;
import org.springframework.validation.annotation.Validated;
import com.github.pagehelper.PageInfo;
import java.util.List;
import ${package.Entity}.${entity};
import ${package.Entity?replace("entity", "req")}.${entity?replace("Entity", "Req")};
import ${package.Entity?replace("entity", "req")}.${entity?replace("Entity", "SaveReq")};
import ${package.Entity?replace("entity", "view")}.${entity?replace("Entity", "View")};
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import ${package.Service}.${table.serviceName};
import lombok.extern.slf4j.Slf4j;
/**
* <p>
* ${table.comment!} 前端控制器
* </p>
*
* @author ${author}
* @since ${date}
*/
@RestController
@Slf4j
@RequestMapping("/${table.entityPath?replace("Entity", "")}")
public class ${table.controllerName} {
@Autowired
private ${table.serviceName} ${table.entityPath?replace("Entity", "")}Service;
@GetMapping("/list")
public ResponseJson list(${table.entityName?replace("Entity", "Req")} ${table.entityPath?replace("Entity", "Req")}) {
List<${table.entityName?replace("Entity", "View")}> list = ${table.entityPath?replace("Entity", "Service")}.list(${table.entityPath?replace("Entity", "Req")});
return ResponseJson.newResponseJson(list);
}
@GetMapping("/page")
public ResponseJson page(${table.entityName?replace("Entity", "Req")} ${table.entityPath?replace("Entity", "Req")}) {
PageInfo page = ${table.entityPath?replace("Entity", "Service")}.page(${table.entityPath?replace("Entity", "Req")});
return ResponseJson.newResponseJson(page);
}
@GetMapping("/remove")
public ResponseJson remove(@RequestParam("id") String id) {
${table.entityPath?replace("Entity", "Service")}.remove(id);
return ResponseJson.newResponseJson();
}
@PostMapping("/save")
public ResponseJson save(@RequestBody @Validated ${table.entityName?replace("Entity", "SaveReq")} ${table.entityPath?replace("Entity", "SaveReq")}) {
String id = ${table.entityPath?replace("Entity", "Service")}.save(${table.entityPath?replace("Entity", "SaveReq")});
return ResponseJson.newResponseJson(id);
}
@GetMapping("/get/{id}")
public ResponseJson getById(@PathVariable("id") String id) {
${table.entityName?replace("Entity", "View")} ${table.entityPath?replace("Entity", "View")} = ${table.entityPath?replace("Entity", "Service")}.getById(id);
return ResponseJson.newResponseJson(${table.entityPath?replace("Entity", "View")});
}
}
entity.java.ftl
package ${package.Entity};
<#list table.importPackages as pkg>
import ${pkg};
</#list>
<#if entityLombokModel>
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
</#if>
/**
* <p>
* ${table.comment!} 对象
* </p>
*
* @author ${author}
* @since ${date}
*/
<#if entityLombokModel>
@Data
</#if>
<#if table.convert>
@TableName("${table.name}")
</#if>
<#if superEntityClass??>
public class ${entity} extends ${superEntityClass}<#if activeRecord><${entity}></#if> {
<#elseif activeRecord>
public class ${entity} extends Model<${entity}> {
<#else>
public class ${entity} implements Serializable {
</#if>
private static final long serialVersionUID = 1L;
<#-- ---------- BEGIN 字段循环遍历 ---------->
<#list table.fields as field>
<#if field.keyFlag>
<#assign keyPropertyName="${field.propertyName}"/>
</#if>
<#if field.comment!?length gt 0>
/**
* ${field.comment}
*/
</#if>
<#if field.keyFlag>
<#-- 主键 -->
<#if field.keyIdentityFlag>
@TableId(value = "${field.name}", type = IdType.AUTO)
<#elseif idType??>
@TableId(value = "${field.name}", type = IdType.${idType})
<#elseif field.convert>
@TableId("${field.name}")
</#if>
<#-- 普通字段 -->
<#elseif field.fill??>
<#-- ----- 存在字段填充设置 ----->
<#if field.convert>
@TableField(value = "${field.name}", fill = FieldFill.${field.fill})
<#else>
@TableField(fill = FieldFill.${field.fill})
</#if>
<#elseif field.convert>
@TableField("${field.name}")
</#if>
<#-- 乐观锁注解 -->
<#if (versionFieldName!"") == field.name>
@Version
</#if>
<#-- 逻辑删除注解 -->
<#if (logicDeleteFieldName!"") == field.name>
@TableLogic
</#if>
private ${field.propertyType} ${field.propertyName};
</#list>
<#------------ END 字段循环遍历 ---------->
<#if !entityLombokModel>
<#list table.fields as field>
<#if field.propertyType == "boolean">
<#assign getprefix="is"/>
<#else>
<#assign getprefix="get"/>
</#if>
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}) {
</#if>
this.${field.propertyName} = ${field.propertyName};
<#if entityBuilderModel>
return this;
</#if>
}
</#list>
</#if>
<#if entityColumnConstant>
<#list table.fields as field>
public static final String ${field.name?upper_case} = "${field.name}";
</#list>
</#if>
<#if activeRecord>
@Override
protected Serializable pkVal() {
<#if keyPropertyName??>
return this.${keyPropertyName};
<#else>
return null;
</#if>
}
</#if>
<#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>
}
req.java.ftl
package ${package.Entity?replace("entity", "req")};
<#list table.importPackages as pkg>
import ${pkg};
</#list>
<#if entityLombokModel>
import lombok.Data;
import java.math.BigDecimal;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
</#if>
/**
* <p>
* ${table.comment!} 请求对象
* </p>
*
* @author ${author}
* @since ${date}
*/
<#if entityLombokModel>
@Data
</#if>
<#if superEntityClass??>
public class ${entity} extends ${superEntityClass}<#if activeRecord><${entity}></#if> {
<#elseif activeRecord>
public class ${entity} extends Model<${entity}> {
<#else>
public class ${entity?replace("Entity", "Req")} extends BaseReq {
</#if>
}
saveReq.java.ftl
package ${package.Entity?replace("entity", "req")};
<#list table.importPackages as pkg>
import ${pkg};
</#list>
<#if entityLombokModel>
import lombok.Data;
import java.math.BigDecimal;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
</#if>
/**
* <p>
* ${table.comment!} 对象
* </p>
*
* @author ${author}
* @since ${date}
*/
<#if entityLombokModel>
@Data
</#if>
<#if superEntityClass??>
public class ${entity} extends ${superEntityClass}<#if activeRecord><${entity}></#if> {
<#elseif activeRecord>
public class ${entity} extends Model<${entity}> {
<#else>
public class ${entity?replace("Entity", "SaveReq")}{
</#if>
<#-- ---------- BEGIN 字段循环遍历 ---------->
<#list table.fields as field>
<#if field.keyFlag>
<#assign keyPropertyName="${field.propertyName}"/>
</#if>
<#if field.comment!?length gt 0>
/**
* ${field.comment}
*/
</#if>
<#if field.keyFlag>
<#-- 主键 -->
<#if field.keyIdentityFlag>
@TableId(value = "${field.name}", type = IdType.AUTO)
<#elseif idType??>
@TableId(value = "${field.name}", type = IdType.${idType})
<#elseif field.convert>
@TableId("${field.name}")
</#if>
<#-- 普通字段 -->
<#elseif field.fill??>
<#-- ----- 存在字段填充设置 ----->
<#if field.convert>
@TableField(value = "${field.name}", fill = FieldFill.${field.fill})
<#else>
@TableField(fill = FieldFill.${field.fill})
</#if>
<#elseif field.convert>
@TableField("${field.name}")
</#if>
<#-- 乐观锁注解 -->
<#if (versionFieldName!"") == field.name>
@Version
</#if>
<#-- 逻辑删除注解 -->
<#if (logicDeleteFieldName!"") == field.name>
@TableLogic
</#if>
private ${field.propertyType} ${field.propertyName};
</#list>
<#------------ END 字段循环遍历 ---------->
<#if !entityLombokModel>
<#list table.fields as field>
<#if field.propertyType == "boolean">
<#assign getprefix="is"/>
<#else>
<#assign getprefix="get"/>
</#if>
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}) {
</#if>
this.${field.propertyName} = ${field.propertyName};
<#if entityBuilderModel>
return this;
</#if>
}
</#list>
</#if>
<#if entityColumnConstant>
<#list table.fields as field>
public static final String ${field.name?upper_case} = "${field.name}";
</#list>
</#if>
<#if activeRecord>
@Override
protected Serializable pkVal() {
<#if keyPropertyName??>
return this.${keyPropertyName};
<#else>
return null;
</#if>
}
</#if>
<#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>
}
view.java.ftl
package ${package.Entity?replace("entity", "view")};
<#list table.importPackages as pkg>
import ${pkg};
</#list>
<#if entityLombokModel>
import lombok.Data;
import java.math.BigDecimal;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
</#if>
/**
* <p>
* ${table.comment!} 对象
* </p>
*
* @author ${author}
* @since ${date}
*/
<#if entityLombokModel>
@Data
</#if>
<#if superEntityClass??>
public class ${entity} extends ${superEntityClass}<#if activeRecord><${entity}></#if> {
<#elseif activeRecord>
public class ${entity} extends Model<${entity}> {
<#else>
public class ${entity?replace("Entity", "View")} extends BaseView {
</#if>
<#-- ---------- BEGIN 字段循环遍历 ---------->
<#list table.fields as field>
<#if field.keyFlag>
<#assign keyPropertyName="${field.propertyName}"/>
</#if>
<#if field.comment!?length gt 0>
/**
* ${field.comment}
*/
</#if>
<#if field.keyFlag>
<#-- 主键 -->
<#if field.keyIdentityFlag>
@TableId(value = "${field.name}", type = IdType.AUTO)
<#elseif idType??>
@TableId(value = "${field.name}", type = IdType.${idType})
<#elseif field.convert>
@TableId("${field.name}")
</#if>
<#-- 普通字段 -->
<#elseif field.fill??>
<#-- ----- 存在字段填充设置 ----->
<#if field.convert>
@TableField(value = "${field.name}", fill = FieldFill.${field.fill})
<#else>
@TableField(fill = FieldFill.${field.fill})
</#if>
<#elseif field.convert>
@TableField("${field.name}")
</#if>
<#-- 乐观锁注解 -->
<#if (versionFieldName!"") == field.name>
@Version
</#if>
<#-- 逻辑删除注解 -->
<#if (logicDeleteFieldName!"") == field.name>
@TableLogic
</#if>
private ${field.propertyType} ${field.propertyName};
</#list>
<#------------ END 字段循环遍历 ---------->
<#if !entityLombokModel>
<#list table.fields as field>
<#if field.propertyType == "boolean">
<#assign getprefix="is"/>
<#else>
<#assign getprefix="get"/>
</#if>
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}) {
</#if>
this.${field.propertyName} = ${field.propertyName};
<#if entityBuilderModel>
return this;
</#if>
}
</#list>
</#if>
<#if entityColumnConstant>
<#list table.fields as field>
public static final String ${field.name?upper_case} = "${field.name}";
</#list>
</#if>
<#if activeRecord>
@Override
protected Serializable pkVal() {
<#if keyPropertyName??>
return this.${keyPropertyName};
<#else>
return null;
</#if>
}
</#if>
<#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.java.ftl
package ${package.Mapper};
import ${package.Entity}.${entity};
import java.util.List;
import com.github.pagehelper.Page;
import ${package.Entity?replace("entity", "req")}.${entity?replace("Entity", "Req")};
import ${package.Entity?replace("entity", "req")}.${entity?replace("Entity", "SaveReq")};
import org.apache.ibatis.annotations.Param;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
@Mapper
@Repository
public interface ${table.mapperName} {
List<${table.entityName}> selectAll(${table.entityName?replace("Entity", "Req")} ${table.entityPath?replace("Entity", "Req")});
void delete(@Param("id") String id);
${table.entityName} getById(@Param("id") String id);
void update(${table.entityName?replace("Entity", "SaveReq")} ${table.entityPath?replace("Entity", "SaveReq")});
void insert(${table.entityName?replace("Entity", "SaveReq")} ${table.entityPath?replace("Entity", "SaveReq")});
Page<${table.entityName}> selectPage(${table.entityName?replace("Entity", "Req")} ${table.entityPath?replace("Entity", "Req")});
}
mapper.xml.ftl
<?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" 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="findBy${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="findByCondition" 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="deleteBy${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="updateBy${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">
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.java.ftl
package ${package.Service};
import ${package.Entity}.${entity};
import java.util.List;
import ${package.Entity?replace("entity", "req")}.${entity?replace("Entity", "Req")};
import ${package.Entity?replace("entity", "req")}.${entity?replace("Entity", "SaveReq")};
import ${package.Entity?replace("entity", "view")}.${entity?replace("Entity", "View")};
import org.apache.ibatis.annotations.Param;
import com.github.pagehelper.PageInfo;
import java.util.List;
public interface ${table.serviceName} {
List<${table.entityName?replace("Entity", "View")}> list(${table.entityName?replace("Entity", "Req")} ${table.entityPath?replace("Entity", "Req")});
PageInfo page(${table.entityName?replace("Entity", "Req")} ${table.entityPath?replace("Entity", "Req")});
void remove(String id);
String save(${table.entityName?replace("Entity", "SaveReq")} ${table.entityPath?replace("Entity", "SaveReq")});
${table.entityName?replace("Entity", "View")} getById(String id);
}
serviceImpl.java.ftl
package ${package.ServiceImpl};
import ${package.Entity}.${entity};
import java.util.List;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import ${package.Entity?replace("entity", "req")}.${entity?replace("Entity", "Req")};
import ${package.Entity?replace("entity", "req")}.${entity?replace("Entity", "SaveReq")};
import ${package.Entity?replace("entity", "view")}.${entity?replace("Entity", "View")};
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?replace("Entity", "Mapper")};
@Override
public List<${table.entityName?replace("Entity", "View")}> list(${table.entityName?replace("Entity", "Req")} ${table.entityPath?replace("Entity", "Req")}) {
List<${table.entityName?replace("Entity", "View")}> ${table.entityPath?replace("Entity", "View")}s = new BeanUtilsBean2TryCatch<${table.entityName}, ${table.entityName?replace("Entity", "View")}>().copyPropertiesList(${table.entityPath?replace("Entity", "Mapper")}.selectAll(${table.entityPath?replace("Entity", "Req")}), ${table.entityName?replace("Entity", "View")}.class);
return ${table.entityPath?replace("Entity", "View")}s;
}
@Override
public PageInfo page(${table.entityName?replace("Entity", "Req")} ${table.entityPath?replace("Entity", "Req")}) {
Page page = ${table.entityPath?replace("Entity", "Mapper")}.selectPage(${table.entityPath?replace("Entity", "Req")});
PageInfo pageInfo = new PageInfo(page);
pageInfo.setList(new BeanUtilsBean2TryCatch<${table.entityName},${table.entityName?replace("Entity", "View")}>().copyPropertiesList(page.getResult(), ${table.entityName?replace("Entity", "View")}.class));
return pageInfo;
}
@Override
public String save(${table.entityName?replace("Entity", "SaveReq")} ${table.entityPath?replace("Entity", "SaveReq")}) {
// 判断数据库中是否有这条记录
${table.entityName} ${table.entityPath} = ${table.entityPath?replace("Entity", "Mapper")}.getById(${table.entityPath?replace("Entity", "SaveReq")}.getId());
if (${table.entityPath} != null) {
${table.entityPath?replace("Entity", "Mapper")}.update(${table.entityPath?replace("Entity", "SaveReq")});
}else{
${table.entityPath?replace("Entity", "Mapper")}.insert(${table.entityPath?replace("Entity", "SaveReq")});
}
return ${table.entityPath?replace("Entity", "SaveReq")}.getId();
}
@Override
public void remove(String ${table.entityPath?replace("Entity", "")}Id) {
${table.entityPath?replace("Entity", "Mapper")}.delete(${table.entityPath?replace("Entity", "")}Id);
}
@Override
public ${table.entityName?replace("Entity", "View")} getById(String ${table.entityPath?replace("Entity", "")}Id) {
${table.entityName} ${table.entityPath} = ${table.entityPath?replace("Entity", "Mapper")}.getById(${table.entityPath?replace("Entity", "")}Id);
return BeanUtilsBean2TryCatch.copyProperties(${table.entityPath}, ${table.entityName?replace("Entity", "View")}.class);
}
}
5、执行结果