使用Mybatis Plus 自动创建模板文件
程序员文章站
2022-07-10 09:35:58
使用Mybatis Plus 自动创建模板文件0 使用效果![完整视频.gif](https://img-blog.csdnimg.cn/img_convert/2e44ac5b763794f2b64492dacd72cd2e.gif#align=left&display=inline&height=971&margin=[object Object]&name=完整视频.gif&originHeight=971&originWidth=1907&...
使用Mybatis Plus 自动创建模板文件
0 使用效果
使用java进行服务器端编程,最日常的工作就是根据数据库表生成实体类文件了,之前我使用过 mybatis generator,通用Mapper感觉都不是特别好用呀,然后就巴拉了一下 Myabtis plus 的官网还有它的github demo。希望能够自己使用Mybaits Plus 生成满意的文件了,所以就有了这篇文章,研究了一天的结果现在给大家吧!
首先明确一下这篇文章的目标:
- 通过Mybatis plus 生成 Controller ,Service ,ServiceImpl ,Entity,XML,甚至还有自己做项目用到的 C#端的实体类文件哟!
- 后来者修改对应配置就能够使用,节约学习时间。
- 项目例程我放在自己的github中了,欢迎大家来start。
github项目地址: https://github.com/nnlzb66/mybatis-plus-learning.git
话不多说,接下来看一看 Mybatis plus 的生成代码的使用姿势吧。
1 导入相关依赖包
<!--mybatis-plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.4.1</version>
</dependency>
<!-- 由于我这里使用的是FreeMarker作为模板引擎,因此多了一个FreeMarker的包 -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.30</version>
</dependency>
<!-- 习惯使用fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.75</version>
</dependency>
<!--MySQL JDBC驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
2 编写生器代码
首先我们要写入需要生成实体类的表格,如果表格比较多,可以用以下语句查询出来。
-- 查询daily开头的表格,用逗号拼接
select
GROUP_CONCAT(table_name)
from information_schema.`TABLES`
where table_schema = 'shggs'
and table_name like 'daily%'
下边的代码我已经按照官网给的例子给大家整好了,第一次使用的时候,只需要修改对应的配置就好了。
package com.baomidou.mybatisplus.samples.generator;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
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 org.junit.Test;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
/**
* mybatis plus 的代码生成功能,附带全套自定义模板
* @author lizhongbin
* @date 2020-11-27
*/
public class CodeGenerator {
// 作者
private static String AUTHOR = "lizhongbin";
// 生成的实体类忽略表前缀: 不需要则置空
private static String ENTITY_IGNORE_PREFIX = "";
// 表名数组
private static String[] TABLES ="daily_abs,daily_abs_second,daily_cd,daily_cd_credit_profit_gap,daily_cd_profit_gap,daily_comment,daily_drzp,daily_drzp_base_profit_gap,daily_drzp_credit_profit_gap,daily_drzp_profit_gap,daily_jrz,daily_llz,daily_llz_region,daily_llz_term_profit_gap"
.split(",");
// 数据库
private static String DB_URL = "jdbc:mysql://localhost:3306/shggs?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=GMT%2B8";
private static DbType DB_TYPE = DbType.MYSQL;
private static String DB_DRIVER = "com.mysql.cj.jdbc.Driver";
private static String DB_SCHEMA = "shggs";
private static String DB_USER_NAME = "root";
private static String DB_PASSWORD = "123456";
// 输出路径
private static String OUTPUT_PATH = "C:\\working\\idea project\\gushou-data-api\\src\\main";
// 父包名
private static String PARENT_PACKAGE = "com.shgsec.gushoudata_api.daily";
// 下边是分类包名
// 输出包名 = 父包名 + "." + 分类包名
private static String CONTROLLER_PACKAGE = "controller";
private static String SERVICE_PACKAGE = "service";
private static String SERVICE_IMPL_PACKAGE = "service.impl";
private static String MAPPER_PACKAGE = "dao";
private static String ENTITY_PACKAGE = "bean";
private static String C_SHARP_ENTITY_PACKAGE = "DailyReport";
// mapper存放路径 = OUTPUT_PATH + MAPPER_XML_PACKAGE
private static String MAPPER_XML_PACKAGE = "/resources/mapper/daily";
// 模板路径
private static JSONObject templates = new JSONObject();
// 注释掉模板表示不生成该类模板
static{
templates.put("CONTROLLER_TEMPLATE", "templates/controller.java.ftl");
templates.put("SERVICE_TEMPLATE", "templates/service.java.ftl");
templates.put("SERVICE_IMPL_TEMPLATE", "templates/serviceImpl.java.ftl");
templates.put("ENTITY_TEMPLATE", "templates/entity.java.ftl");
templates.put("MAPPER_TEMPLATE", "templates/mapper.java.ftl");
templates.put("MAPPER_XML_TEMPLATE", "templates/mapper.xml.ftl");
// templates.put("C_SHARP_ENTITY_TEMPLATE", "templates/C#entity.cs.ftl");
}
// 生成的实体类尾缀 例如: UserEntity
private static String Entity_SUFFIX = "Entity";
public static void main(String args[]){
// 全局配置
GlobalConfig globalConfig = globalConfig();
// 数据库连接配置
DataSourceConfig dataSourceConfig = dataSourceConfig();
// 策略配置
StrategyConfig strategyConfig = strategyConfig();
// 包配置
PackageConfig packageConfig = packageConfig();
// 模板配置
TemplateConfig templateConfig = templateConfig();
// 自定义配置
InjectionConfig injectionConfig = injectionConfig();
// 执行
AutoGenerator autoGenerator = new AutoGenerator();
autoGenerator.setGlobalConfig(globalConfig)
.setDataSource(dataSourceConfig)
.setStrategy(strategyConfig)
.setPackageInfo(packageConfig)
// 因为使用了自定义模板,所以需要把各项置空否则会多生成一次
.setTemplate(templateConfig)
// 使用的模板引擎,如果不是默认模板引擎则需要添加模板依赖到pom,现在用的是freemarker,需要导包
.setTemplateEngine(new FreemarkerTemplateEngine())
.setCfg(injectionConfig)
.execute();
// 用于查看配置中都有什么,方便写ftl模板时候自己去找配置,写到ftl中
// System.out.println("================= 配置信息 =======================");
// System.out.println(JSON.toJSONString(autoGenerator.getConfig(), SerializerFeature.PrettyFormat));
// List<TableInfo> list = autoGenerator.getConfig().getTableInfoList();
// for (TableInfo t:list) {
// System.out.println("================= 表格信息 =======================");
// System.out.println(JSON.toJSONString(t,SerializerFeature.PrettyFormat));
// }
}
/**
* 全局配置
*/
private static GlobalConfig globalConfig() {
return new GlobalConfig()
// 打开文件
.setOpen(false)
// 文件覆盖
.setFileOverride(true)
// 开启activeRecord模式,开启之后就可以直接使用entity对数据库进行操作
.setActiveRecord(true)
// XML ResultMap: mapper.xml生成查询映射结果
.setBaseResultMap(true)
// XML ColumnList: mapper.xml生成查询结果列
.setBaseColumnList(true)
// swagger注解; 须添加swagger依赖
.setSwagger2(true)
// 作者
.setAuthor(AUTHOR)
// 设置实体类后缀名称
.setEntityName("%s"+Entity_SUFFIX);
}
/**
* 数据源配置
*/
private static DataSourceConfig dataSourceConfig() {
// 数据源配置
return new DataSourceConfig()
// 地址
.setUrl(DB_URL)
// 数据库名
.setSchemaName(DB_SCHEMA)
// 驱动
.setDriverName(DB_DRIVER)
// 用户名
.setUsername(DB_USER_NAME)
// 密码
.setPassword(DB_PASSWORD)
// 数据库类型
.setDbType(DB_TYPE);
}
/**
* 策略配置
*/
private static StrategyConfig strategyConfig() {
return new StrategyConfig()
// 表名生成策略:下划线连转驼峰
.setNaming(NamingStrategy.underline_to_camel)
// 表字段生成策略:下划线连转驼峰
.setColumnNaming(NamingStrategy.underline_to_camel)
// 需要生成的表
.setInclude(TABLES)
// 生成controller
.setRestControllerStyle(true)
// 去除表前缀
.setTablePrefix(ENTITY_IGNORE_PREFIX)
// controller映射地址:驼峰转连字符
.setControllerMappingHyphenStyle(true)
// 是否为lombok模型; 需要lombok依赖
.setEntityLombokModel(true)
// 生成实体类字段注解
.setEntityTableFieldAnnotationEnable(true);
}
/**
* 包配置
* 设置包路径用于导包时使用,路径示例:com.path
*/
private static PackageConfig packageConfig() {
return new PackageConfig()
// 如果下面包没写全,还有前缀那就加上,如果包写全了就不加了
.setParent(PARENT_PACKAGE)
.setController(CONTROLLER_PACKAGE)
.setService(SERVICE_PACKAGE)
.setServiceImpl(SERVICE_IMPL_PACKAGE)
.setEntity(ENTITY_PACKAGE)
.setMapper(MAPPER_PACKAGE)
.setXml(MAPPER_PACKAGE);
}
/**
* 模板配置
*/
private static TemplateConfig templateConfig() {
return new TemplateConfig()
// 置空后方便使用自定义输出位置
.setEntity(null)
.setXml(null)
.setMapper(null)
.setService(null)
.setServiceImpl(null)
.setController(null);
}
/**
* 自定义配置
*/
private static InjectionConfig injectionConfig() {
// 自定义日期和日期格式
SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
String dateString = format.format(new Date());
Map<String,Object> userDefiedData = new HashMap<>();
userDefiedData.put("createTime", dateString);
userDefiedData.put("schema", DB_SCHEMA);
return new InjectionConfig() {
@Override
public void initMap() {
// 注入配置
}
}
// 判断是否创建文件
.setFileCreate(new IFileCreate() {
@Override
public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
// 检查文件目录,不存在自动递归创建
createFile(filePath);
// 指定需要覆盖的文件, 文件不存在就创建,否则只覆盖Dao,Mapper.xml,Mapper.java,Model.cs
if (isExists(filePath)
&& (!filePath.endsWith("Mapper.xml")
&& !filePath.endsWith(Entity_SUFFIX+".java")
&& !filePath.endsWith("Mapper.java")
&& !filePath.endsWith("Model.cs")
)) {
return false;
}
return true;
}
})
// 自定义输出文件
.setFileOutConfigList(fileOutConfigList())
// 自定义参数使用cfg.xxx来调用
.setMap(userDefiedData);
}
/**
* 自定义输出文件配置
*/
private static List<FileOutConfig> fileOutConfigList() {
List<FileOutConfig> list = new ArrayList<>();
String CONTROLLER_TEMPLATE = templates.getString("CONTROLLER_TEMPLATE");
String SERVICE_TEMPLATE = templates.getString("SERVICE_TEMPLATE");
String SERVICE_IMPL_TEMPLATE = templates.getString("SERVICE_IMPL_TEMPLATE");
String ENTITY_TEMPLATE = templates.getString("ENTITY_TEMPLATE");
String MAPPER_TEMPLATE = templates.getString("MAPPER_TEMPLATE");
String MAPPER_XML_TEMPLATE = templates.getString("MAPPER_XML_TEMPLATE");
String C_SHARP_ENTITY_TEMPLATE = templates.getString("C_SHARP_ENTITY_TEMPLATE");
// 实体类文件输出
list.add(new FileOutConfig(ENTITY_TEMPLATE) {
@Override
public String outputFile(TableInfo tableInfo) {
return OUTPUT_PATH + "/java/" + replaceDot(PARENT_PACKAGE,ENTITY_PACKAGE) +"/"+ tableInfo.getEntityName() + StringPool.DOT_JAVA;
}
});
// C#实体类文件输出
list.add(new FileOutConfig(C_SHARP_ENTITY_TEMPLATE) {
@Override
public String outputFile(TableInfo tableInfo) {
return OUTPUT_PATH + "/java/" + replaceDot(PARENT_PACKAGE,C_SHARP_ENTITY_PACKAGE) +"/"+ tableInfo.getEntityName() + ".cs";
}
});
// mapper xml文件输出
list.add(new FileOutConfig(MAPPER_XML_TEMPLATE) {
@Override
public String outputFile(TableInfo tableInfo) {
return OUTPUT_PATH + replaceDot("",MAPPER_XML_PACKAGE) +"/"+ tableInfo.getXmlName() + StringPool.DOT_XML;
}
});
// mapper文件输出
list.add(new FileOutConfig(MAPPER_TEMPLATE) {
@Override
public String outputFile(TableInfo tableInfo) {
return OUTPUT_PATH + "/java/" + replaceDot(PARENT_PACKAGE,MAPPER_PACKAGE) +"/"+ tableInfo.getMapperName() + StringPool.DOT_JAVA;
}
});
// service文件输出
list.add(new FileOutConfig(SERVICE_TEMPLATE) {
@Override
public String outputFile(TableInfo tableInfo) {
return OUTPUT_PATH + "/java/" + replaceDot(PARENT_PACKAGE,SERVICE_PACKAGE) +"/"+ tableInfo.getServiceName() + StringPool.DOT_JAVA;
}
});
// service impl文件输出
list.add(new FileOutConfig(SERVICE_IMPL_TEMPLATE) {
@Override
public String outputFile(TableInfo tableInfo) {
return OUTPUT_PATH + "/java/" + replaceDot(PARENT_PACKAGE,SERVICE_IMPL_PACKAGE)+"/" + tableInfo.getServiceImplName() + StringPool.DOT_JAVA;
}
});
// controller文件输出
list.add(new FileOutConfig(CONTROLLER_TEMPLATE) {
@Override
public String outputFile(TableInfo tableInfo) {
return OUTPUT_PATH + "/java/" + replaceDot(PARENT_PACKAGE,CONTROLLER_PACKAGE)+"/" + tableInfo.getControllerName() + StringPool.DOT_JAVA;
}
});
return list;
}
/**
* 判断文件是否存在
* @param path 路径
* @return
*/
private static boolean isExists(String path) {
File file = new File(path);
return file.exists();
}
/**
* 将.替换成为文件分隔符
* */
private static String replaceDot(String parent,String value){
return (parent+"."+value).replaceAll("\\.","/");
}
/**
* 自动创建
*/
private static void createFile(String filePath){
File file = new File(filePath);
if(!file.exists()){
File folder = file.getParentFile();
if(!folder.exists()){
folder.mkdirs();
}
file = new File(filePath);
}
}
}
3 编写模板文件代码
3.1 contoller.java.ftl
package ${package.Controller};
import ${package.Entity}.${entity};
import ${package.Service}.${table.serviceName};
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.alibaba.fastjson.JSON;
<#if restControllerStyle>
<#else>
import org.springframework.stereotype.Controller;
</#if>
<#if superControllerClassPackage??>
import ${superControllerClassPackage};
</#if>
import javax.validation.Valid;
import java.util.List;
/**
* <p>
* ${table.comment} 前端控制器
* </p>
*
* @author ${author}
* @date ${date}
*/
@Api(tags = "${table.comment}")
<#if restControllerStyle>
@RestController
<#else>
@Controller
</#if>
@RequestMapping("<#if package.ModuleName??>/${package.ModuleName}</#if>/<#if controllerMappingHyphenStyle??>${controllerMappingHyphen}<#else>${table.entityPath}</#if>")
<#if kotlin>
class ${table.controllerName}<#if superControllerClass??> : ${superControllerClass}()</#if>
<#else>
<#if superControllerClass??>
public class ${table.controllerName} extends ${superControllerClass} {
<#else>
public class ${table.controllerName} {
</#if>
@Autowired
private ${table.serviceName} ${table.serviceName?uncap_first};
@ApiOperation(value = "${table.comment}分页列表", response = ${entity}.class)
@ApiImplicitParams({
@ApiImplicitParam(name = "page", value = "页面", dataType = "Long"),
@ApiImplicitParam(name = "size", value = "页面数据量", dataType = "Long"),
@ApiImplicitParam(name = "sort", value = "排序方式排序[true:正序; false:倒序]", dataType = "Boolean"),
@ApiImplicitParam(name = "sortName", value = "排序字段,参照返回字段", dataType = "String")})
@PostMapping(value = "/page")
public String list(@Valid @RequestBody ${entity} param) {
try{
List<${entity}> data = ${table.serviceName?uncap_first}.list(param);
return JSON.toJSONString(data);
}catch(Exception e){
return e.getMessage();
}
}
@ApiOperation(value = "${table.comment}详情", response = ${entity}.class)
@GetMapping(value = "/info/{id}")
public String info(@PathVariable Long id) {
try{
${entity} data = ${table.serviceName?uncap_first}.info(id);
return JSON.toJSONString(data);
}catch(Exception e){
return e.getMessage();
}
}
@ApiOperation(value = "${table.comment}新增")
@PostMapping(value = "/add")
public String add(@Valid @RequestBody ${entity} param) {
try{
${table.serviceName?uncap_first}.add(param);
return "发送成功!";
}catch(Exception e){
return e.getMessage();
}
}
@ApiOperation(value = "${table.comment}修改")
@PostMapping(value = "/modify")
public Object modify(@Valid @RequestBody ${entity} param) {
try{
${table.serviceName?uncap_first}.modify(param);
return "修改成功!";
}catch(Exception e){
return e.getMessage();
}
}
@ApiOperation(value = "${table.comment}删除(单个条目)")
@GetMapping(value = "/remove/{id}")
public Object remove(@PathVariable Long id) {
try{
${table.serviceName?uncap_first}.remove(id);
return "删除成功!";
}catch(Exception e){
return e.getMessage();
}
}
@ApiOperation(value = "${table.comment}删除(多个条目)")
@PostMapping(value = "/removes")
public Object removes(@Valid @RequestBody List<Long> ids) {
try{
${table.serviceName?uncap_first}.removes(ids);
return "批量删除成功!";
}catch(Exception e){
return e.getMessage();
}
}
}
</#if>
3.2 service.java.ftl
package ${package.Service};
import ${package.Entity}.${entity};
import ${superServiceClassPackage};
import java.util.List;
/**
* ${table.comment!} 服务类
*
* @author ${author}
* @date ${date}
*/
public interface ${table.serviceName} extends ${superServiceClass}<${entity}> {
/**
* ${table.comment!}查询列表
* @param param 根据需要进行传值
* @return
*/
List<${entity}> list(${entity} param) throws Exception;
/**
* ${table.comment!}详情
* @param id
* @return
*/
${entity} info(Long id) throws Exception;
/**
* ${table.comment!}新增
* @param param 根据需要进行传值
* @return
*/
void add(${entity} param) throws Exception;
/**
* ${table.comment!}修改
* @param param 根据需要进行传值
* @return
*/
void modify(${entity} param) throws Exception;
/**
* ${table.comment!}删除(单个条目)
* @param id
* @return
*/
void remove(Long id) throws Exception;
/**
* 删除(多个条目)
* @param ids
* @return
*/
void removes(List<Long> ids) throws Exception;
}
3.3 serviceImpl.java.ftl
package ${package.ServiceImpl};
import ${package.Entity}.${entity};
import ${package.Mapper}.${table.mapperName};
import ${package.Service}.${table.serviceName};
import ${superServiceImplClassPackage};
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.List;
import com.alibaba.fastjson.JSON;
import java.util.List;
/**
* ${table.comment!} 服务实现类
*
* @author ${author}
* @date ${date}
*/
@Service
<#if kotlin>
open class ${table.serviceImplName} : ${superServiceImplClass}<${table.mapperName}, ${entity}>(), ${table.serviceName} {
}
<#else>
public class ${table.serviceImplName} extends ${superServiceImplClass}<${table.mapperName}, ${entity}> implements ${table.serviceName} {
/**
* ${table.comment!}查询列表
* @param param 根据需要进行传值
* @return
*/
@Override
public List<${entity}> list(${entity} param) {
QueryWrapper<${entity}> queryWrapper = new QueryWrapper<>();
queryWrapper.lambda()
<#list table.fields as field>
// ${field.comment}
<#if !entityLombokModel>
<#if field.propertyType == "Boolean">
<#assign getprefix="is"/>
<#else>
<#assign getprefix="get"/>
</#if>
<#if field.propertyType == "String">
.eq(!StringUtils.isEmpty(param.${getprefix}${field.capitalName}()), ${entity}::${getprefix}${field.capitalName}, param.${getprefix}${field.capitalName}())
<#else>
.eq(param.${getprefix}${field.capitalName}() != null, ${entity}::${getprefix}${field.capitalName}, param.${getprefix}${field.capitalName}())
</#if>
<#else>
<#if field.propertyType == "String">
.eq(!StringUtils.isEmpty(param.get${field.capitalName}()), ${entity}::get${field.capitalName}, param.get${field.capitalName}())
<#else>
.eq(param.get${field.capitalName}() != null, ${entity}::get${field.capitalName}, param.get${field.capitalName}())
</#if>
</#if>
</#list>;
List<${entity}> result = list(queryWrapper);
return result;
}
/**
* ${table.comment!}详情
* @param id
* @return
*/
@Override
public ${entity} info(Long id) {
return getById(id);
}
/**
* ${table.comment!}新增
* @param param 根据需要进行传值
* @return
*/
@Override
public void add(${entity} param) throws Exception {
if (!save(param)) {
throw new Exception("添加"+JSON.toJSONString(param)+"失败!");
}
}
/**
* ${table.comment!}修改
* @param param 根据需要进行传值
* @return
*/
@Override
public void modify(${entity} param) throws Exception {
if (!updateById(param)) {
throw new Exception("修改"+JSON.toJSONString(param)+"失败!");
}
}
/**
* ${table.comment!}删除(单个条目)
* @param id
* @return
*/
@Override
public void remove(Long id) throws Exception {
if (!removeById(id)) {
throw new Exception("删除: "+id+" 失败!");
}
}
/**
* ${table.comment!}删除(多个条目)
* @param ids
* @return
*/
@Override
public void removes(List<Long> ids) throws Exception {
removeByIds(ids);
}
}
</#if>
3.4 mapper.java.ftl
package ${package.Mapper};
import ${package.Entity}.${table.entityName};
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* @author ${author}
* @date ${date}
*/
public interface ${table.mapperName} extends BaseMapper<${table.entityName}> {
// 自定义自增主键插入
public int insertOne(${table.entityName} entity);
}
3.5 entity.java.ftl
package ${package.Entity};
import lombok.Data;
import java.math.BigDecimal;
import java.util.Date;
/**
${table.comment}
@author ${author}
@date ${cfg.createTime}
*/
@Data
public class ${entity} {
<#list table.commonFields as value>
<#if value.comment!="">
// ${value.comment}
</#if>
private ${value.propertyType} ${value.capitalName};
</#list>
<#list table.fields as value>
<#if value.comment!="">
// ${value.comment}
</#if>
private ${value.propertyType} ${value.capitalName};
</#list>
}
3.6 mapper.xml.ftl
<#function transType javaType>
<#local result = "">
<#switch javaType>
<#case "BigDecimal"><#local result = "java.math.BigDecimal"><#break>
<#case "Date"><#local result = "java.util.Date"><#break>
<#default> <#local result = javaType>
</#switch>
<#return result>
</#function>
<?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.entityName}Mapper">
<resultMap id="BaseResultMap" type="${package.Entity}.${table.entityName}">
<#list table.commonFields as value>
<result column="${value.propertyName}" property="${value.capitalName}" jdbcType="${value.columnType}" javaType="${transType(value.propertyType)}"></result>
</#list>
<#list table.fields as value>
<result column="${value.propertyName}" property="${value.capitalName}" jdbcType="${value.columnType}" javaType="${transType(value.propertyType)}"></result>
</#list>
</resultMap>
<!-- 自定义自增主键插入 -->
<insert id="insertOne" parameterType="${package.Entity}.${table.entityName}">
<selectKey resultType="Long" keyColumn="id" keyProperty="id">
select max(id)
from
${table.name}
</selectKey>
insert into ${table.name}
(
<#list table.fields as value>
<#if value_index = table.fields?size-1>
${value.columnName}
<#else>
${value.columnName},
</#if>
</#list>
) values
(
<#list table.fields as value>
<#if value_index = table.fields?size-1>
<#noparse>#{</#noparse>${value.capitalName}<#noparse>}</#noparse>
<#else>
<#noparse>#{</#noparse>${value.capitalName}<#noparse>},</#noparse>
</#if>
</#list>
)
</insert>
</mapper>
3.7 最骚的操作来啦,甚至还可以生成C#的文件呢,反正是模板,你想怎么生成就怎么生成!
using System;
<#function transType javaType>
<#local result = "">
<#switch javaType>
<#case "Long"><#local result = "long"><#break>
<#case "Integer"><#local result = "int"><#break>
<#case "Boolean"><#local result = "bool"><#break>
<#case "BigDecimal"><#local result = "decimal"><#break>
<#case "String"><#local result = "string"><#break>
<#case "Float"><#local result = "float"><#break>
<#case "Double"><#local result = "double"><#break>
<#case "Short"><#local result = "short"><#break>
<#case "Byte"><#local result = "byte"><#break>
<#default> <#local result = javaType>
</#switch>
<#return result>
</#function>
namespace ShgFICCDataAnaClient.Model.DailyReport
{
/// <summary>
/// ${table.comment}
/// </summary>
public class ${entity}Model : ShgModelBase
{
<#list table.commonFields as value>
<#if value.comment!="">
// ${value.comment}
</#if>
private ${transType(value.propertyType)} _${value.columnName};
</#list>
<#list table.fields as value>
<#if value.comment!="">
// ${value.comment}
</#if>
private ${transType(value.propertyType)} _${value.columnName};
</#list>
<#list table.commonFields as value>
public ${transType(value.propertyType)} ${value.capitalName} { get { return _${value.columnName}; } set { _${value.columnName} = value; } };
</#list>
<#list table.fields as value>
public ${transType(value.propertyType)} ${value.capitalName} { get { return _${value.columnName}; } set { _${value.columnName} = value; } }
</#list>
}
}
4 接下来,美好的事情即将发生……
从Github 上导入程序之后,修改项目配置,点击RunMain,具体效果请看文章开头,哈哈哈!
本文地址:https://blog.csdn.net/nnlzb66/article/details/110236124
推荐阅读
-
SSM框架学习:使用MyBatis Generator自动创建代码
-
vim创建程序文件自动添加头部注释/自动文件头注释与模板定义
-
Unity 基础 之 新创建脚本的时候自动添加头部格式模板注释/开始处文件描述(文件头规范)
-
Mybatis-Plus中使用乐观锁、时间自动填充、逻辑删除。
-
使用Mybatis Plus 自动创建模板文件
-
SpringBoot项目使用mybatis-plus逆向自动生成全套代码
-
mybatis-plus 使用Generator 工具类自动生成dao 实体类 service mapper类
-
详解使用Mybatis-plus + velocity模板生成自定义的代码
-
SpringBoot集成Mybatis-plus并实现自动生成相关文件的示例代码
-
使用MyBatis-Generator如何自动生成映射文件