1雪情、創(chuàng)建表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>
<!-- 擴(kuò)展代碼生成插件 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、新建生成器類(lèi)(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 {
/**
* 讀取控制臺(tái)內(nèi)容
*/
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("請(qǐng)輸入" + tip + ":");
System.out.println(help.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotEmpty(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("請(qǐng)輸入正確的" + 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");
//是否打開(kāi)輸出目錄
gc.setOpen(false);
//是否覆蓋已有文件
gc.setFileOverride(true);
gc.setBaseColumnList(true);
gc.setBaseResultMap(true);
gc.setSwagger2(true); // 實(shí)體屬性 Swagger2 注解
//service 命名方式
gc.setServiceName("%sService");
//entity 命名方式
gc.setEntityName("%sEntity");
mpg.setGlobalConfig(gc);
// 數(shù)據(jù)源配置
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) {
//如果不存在痕慢,創(chuàng)建;如果存在涌矢,判斷是否是entity.java:如果是掖举,創(chuàng)建(覆蓋);否則娜庇,不創(chuàng)建塔次。
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<>();
// 自定義配置會(huì)被優(yōu)先輸出
focList.add(new FileOutConfig(mapperPath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定義輸出文件名 , 如果你 Entity 設(shè)置了前后綴名秀、此處注意 xml 的名稱(chēng)會(huì)跟著發(fā)生變化@骸!
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 設(shè)置了前后綴继榆、此處注意 xml 的名稱(chēng)會(huì)跟著發(fā)生變化!汁掠!
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 設(shè)置了前后綴、此處注意 xml 的名稱(chēng)會(huì)跟著發(fā)生變化?稼濉翠忠!
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 設(shè)置了前后綴乞榨、此處注意 xml 的名稱(chēng)會(huì)跟著發(fā)生變化;嘀当娱!
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 設(shè)置了前后綴政溃、此處注意 xml 的名稱(chēng)會(huì)跟著發(fā)生變化V悍谩!
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, 會(huì)根據(jù)使用的模板引擎自動(dòng)識(shí)別
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();
//數(shù)據(jù)庫(kù)表映射到實(shí)體的命名策略
strategy.setNaming(NamingStrategy.underline_to_camel);
//數(shù)據(jù)庫(kù)表字段映射到實(shí)體的命名策略, 未指定按照 naming 執(zhí)行
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
//字段前綴
strategy.setFieldPrefix("R_","T_","D_","I_","N_");
strategy.setInclude(scanner("表名扼鞋,多個(gè)英文逗號(hào)分割").split(","));
//駝峰轉(zhuǎn)連字符
strategy.setControllerMappingHyphenStyle(true);
// strategy.setTablePrefix(pc.getModuleName() + "_");
//tablePrefix
strategy.setTablePrefix("survey" + "_");
//Boolean類(lèi)型字段是否移除is前綴
strategy.setEntityBooleanColumnRemoveIsPrefix(true);
//邏輯刪除屬性名稱(chēng)
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!} 對(duì)象
* </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 字段循環(huán)遍歷 ---------->
<#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??>
<#-- ----- 存在字段填充設(shè)置 ----->
<#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>
<#-- 樂(lè)觀鎖注解 -->
<#if (versionFieldName!"") == field.name>
@Version
</#if>
<#-- 邏輯刪除注解 -->
<#if (logicDeleteFieldName!"") == field.name>
@TableLogic
</#if>
private ${field.propertyType} ${field.propertyName};
</#list>
<#------------ END 字段循環(huán)遍歷 ---------->
<#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!} 請(qǐng)求對(duì)象
* </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!} 對(duì)象
* </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 字段循環(huán)遍歷 ---------->
<#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??>
<#-- ----- 存在字段填充設(shè)置 ----->
<#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>
<#-- 樂(lè)觀鎖注解 -->
<#if (versionFieldName!"") == field.name>
@Version
</#if>
<#-- 邏輯刪除注解 -->
<#if (logicDeleteFieldName!"") == field.name>
@TableLogic
</#if>
private ${field.propertyType} ${field.propertyName};
</#list>
<#------------ END 字段循環(huán)遍歷 ---------->
<#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!} 對(duì)象
* </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 字段循環(huán)遍歷 ---------->
<#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??>
<#-- ----- 存在字段填充設(shè)置 ----->
<#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>
<#-- 樂(lè)觀鎖注解 -->
<#if (versionFieldName!"") == field.name>
@Version
</#if>
<#-- 邏輯刪除注解 -->
<#if (logicDeleteFieldName!"") == field.name>
@TableLogic
</#if>
private ${field.propertyType} ${field.propertyName};
</#list>
<#------------ END 字段循環(huán)遍歷 ---------->
<#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}">
<!-- 通用設(shè)置 -->
<#if baseColumnList>
<!-- 通用查詢(xún)列 -->
<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>
<!-- 通用設(shè)置列 -->
<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>
<!-- 通用查詢(xún)映射結(jié)果 -->
<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>
<!-- 查詢(xún)表${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>
<!-- 根據(jù)主鍵${field.propertyName}查詢(xún)表${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>
<!-- 根據(jù)條件查詢(xún)表${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>
<!-- 根據(jù)主鍵${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>
<!-- 根據(jù)主鍵${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")}) {
// 判斷數(shù)據(jù)庫(kù)中是否有這條記錄
${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愤诱、執(zhí)行結(jié)果