MybatisPlus自定义代码生成模板-mybatisplus代码生成器模板中的参数
1. 需要提前了解 Freemarker 模板语法
一、freemarker模板文件(*.ftl)的基本组成部分
- 文本:直接输出的内容部分
- 注释:不会输出的内容,格式为<#-- 注释内容 -->
- 取值(插值):代替输出数据模型的部分,格式为${数据模型}或#
- ftl指令:Freemarker指令,类似于HTML标记。
1. 内建指令:开始标签:<#directivename parameter> 结束标签:</#directivename>
2. 空标签:<#directivename parameter/>
3. 自定义指令:开始标签:<@directivename parameter> 结束标签:<@directivename>
4. 空标签:<@directivename parameter/>
至于什么是内建指令,什么是自定义指令 我会在下面叙述到。
二、Freemarker语法及使用方法
-
取值(插值)指令及适用类型:
-
${var}
适用类型:java中常用的八大基本类型以及我们的String引用类型,但是,freemarker中boolean类型显示时trueyes,falseno
在后台文件中定义变量
String strVar = "世界你好";
int intVar = 10;
boolean booVar = true;
在页面中获取变量:
String获取:${strVar}
int获取:${intVar}
boolean获取:${booVar?string("yes","no")}
展示结果:
String获取:世界你好
int获取:10
boolean获取:yes -
${var!}
适用类型:对 null 或者不存在的对象进行取值,可以设置默认值,例:${var!'我是默认值'} 即,有值时显示正常值,无值时显示默认值
示例: -
在后台文件中定义变量
String strVar = "世界你好";
String str = null; -
在页面中获取变量:
String获取:${strVar!"我是空"}
str获取:${str!}
str获取:${str!"默认"}
展示结果:
String获取:世界你好
str获取:
str获取:默认 -
${封装对象.属性}
适用类型:对封装对象进行取值,例:${User.name}
示例:
在后台文件中封装对象User[ name, age ]
String name = "姓名";
int age = 18;
在页面中获取变量:
name获取:${User.name}
age获取:${User.age}
展示结果:
name获取:姓名
age获取:18 -
${date?String('yyyy-MM-dd')}
适用类型:对日期格式进行取值,在这里我要强调的是,定义Date类型的变量时,java.util.Date无法输出日期,须使用java.sql.Date
示例:
在后台文件中定义变量
java.sql.Date date = new Date().getTime();
java.sql.Date time = new Date().getTime();
java.sql.Date datetime = new Date().getTime();
在页面中获取变量:
date获取:${date?string('yyyy-MM-dd')}
time获取:${date?string('HH:mm:ss')}
datetime获取:${date?string('yyyy-MM-dd HH:mm:ss')}
展示结果:
name获取:姓名
age获取:18 -
${var?html}
适用类型:转义HTML内容
示例:
在后台文件中封装变量Menu[ name, model ]
Menu m = new Menu();
m.setName(" freemarker ");
m.setModel("我只是个菜单");
在页面中获取变量:
非转义获取:${m.model}
转义获取: ${m.model?html}
展示结果:
非转义获取:我只是个菜单
转义获取:我只是个菜单 -
<#assign num = 100 />
适用类型:定义变量,支持计算和赋值
示例:
在页面中定义变量:
<#assign num = 100 />
num获取:${num)}
计算结果:${num * 10}
展示结果:
num获取:100
计算结果:1000 -
对List集合进行取值
<#list list集合 as item>
${item} --取值
</#list>
示例:
在后台文件中定义变量
ListstrList = new ArrayList ();
strList.add("第一个值");
strList.add("第二个值");
strList.add("第三个值");
在页面中获取变量:
<#list strList as item>
${item!}
--取值
</#list>
展示结果:
第一个值
第二个值
第三个值 -
对Map集合进行取值
<#list map?keys as key>
${key}😒{map[key]}
</#list>
示例:
在后台文件中定义变量
Map<String, Object> m = new HashMap<String, Object>();
m.put("name","姓名");
m.put("age",18);
m.put("sex","男");
在页面中获取变量:
<#list m?keys as key>
${key}😒{m[key]}
</#list>
展示结果:
name:姓名
age:18
sex:男 -
条件判断指令:
1. if
格式:<#if 条件>
输出
</#if>
示例:
在页面中定义变量并判断条件:
<#assign age = 18 />
<#if age == 18>
age = 18
</#if>
展示结果:
age = 18
2. if - else
格式:<#if 条件>
输出
<#else>
输出
</#if>
示例:
在页面中定义变量并判断条件:
<#assign age = 20 />
<#if age == 18>
age = 18
<#else>
age != 18
</#if>
展示结果:
age != 18
3. if - elseif - else
格式:<#if 条件1>
输出
<#elseif 条件2>
输出
<#else>
输出
</#if>
示例:
在页面中定义变量并判断条件:
<#assign age = 20 />
<#if age > 18>
青年
<#elseif age == 18>
成年<
<#else>
少年
</#if>
展示结果:
成年
4. switch --常与case break default一起使用 参数可为字符串
格式:<#switch var>
<#case 条件1>
输出
<#break>
<#case 条件2>
输出
<#break>
<#default>
输出
</#switch>
示例:
在页面中定义变量并判断:
<#switch var="星期一">
<#case "星期一">
油焖大虾
<#break>
<#case "星期二">
炸酱面
<#break>
<#default>
肯德基
</#switch>
展示结果:
油焖大虾 -
自定义函数、自定义指令:
1. 自定义函数
实现TemplateMthodModelEx
2. 自定义指令
实现TemplateDirectiveModel
示例:
<@自定义指令名称 入参(key-value格式) ; 出参(list格式)>
运行条件
</@自定义指令名称> -
常用内建函数、macro(宏指令)、function(函数指令):
1. 常用内建函数
处理字符串:
substring 截取字符串,包头不包尾(下标)
cap_first 第一个字母大写
end_with 以什么字母结尾
contains 是否包含目标字符串
date datetime time 转换成日期格式
starts_with 以什么字母开头
index_of 返回某个指定的字符串值在字符串中首次出现的位置(下标)
last_index_of 获取指定字符出现的最后位置(下标)
split 分隔
trim 去两端空格
处理数字:
string
x?string("0.##") 变成小数点后几位
round 四舍五入
floor 去掉小数点
ceiling 近1 变成整数
处理list:
first: 取List值第一个值
last: 取List值最后一个值
seq_contains: 是否包含指定字符
seq_index_of: 指定字符所在位置
size: 集合大小
reverse: 集合倒序排列
sort: 对集合进行排序
sort_by: 根据某一个属性排序
chunk: 分块处理
其他:
is_string: 是否为字符类型
is_number: 是否为整数类型
is_method: 是否为方法
2. 判断整个变量
has_content: 判断对象是否为空或不存在
eval: 求值
3. macro(宏指令)
调用:<@macro_name param />
语法:<#macro 变量名 参数>
<#nested/>
</#macro>
4. function(函数指令)
调用:${function_name(param)}
语法:<#function 变量名 参数>
<#return>
</#function>
2. MybatisPlus 为我们提供了哪些参数
{
"date": "2018-10-30",
"superServiceImplClassPackage": "com.baomidou.mybatisplus.extension.service.impl.ServiceImpl",
"baseResultMap": true,
"superMapperClass": "BaseMapper",
"activeRecord": true,
"superServiceClass": "IService",
"superServiceImplClass": "ServiceImpl",
"table": {
"comment": "查询指定城市所有测点的空气质量实况每小时更新",
"commonFields": [],
"controllerName": "AirStatLiveDataController",
"convert": false,
"entityName": "AirStatLiveData",
"entityPath": "airStatLiveData",
"fieldNames": "table_id, citycode, cityname, createtime, time, info, devid, stationname, aqi, pm25, pm10, co, so2, no2, o3, prkey",
"fields": [{
"capitalName": "TableId",
"columnType": "LONG",
"comment": "表单id",
"convert": false,
"keyFlag": true,
"keyIdentityFlag": true,
"name": "table_id",
"propertyName": "tableId",
"propertyType": "Long",
"type": "bigint(20)"
}, {
"capitalName": "Citycode",
"columnType": "STRING",
"comment": "城市编码",
"convert": false,
"keyFlag": false,
"keyIdentityFlag": false,
"name": "citycode",
"propertyName": "citycode",
"propertyType": "String",
"type": "varchar(50)"
}, {
"capitalName": "Cityname",
"columnType": "STRING",
"comment": "城市名称",
"convert": false,
"keyFlag": false,
"keyIdentityFlag": false,
"name": "cityname",
"propertyName": "cityname",
"propertyType": "String",
"type": "varchar(50)"
}, {
"capitalName": "Createtime",
"columnType": "STRING",
"comment": "数据更新时间",
"convert": false,
"keyFlag": false,
"keyIdentityFlag": false,
"name": "createtime",
"propertyName": "createtime",
"propertyType": "String",
"type": "varchar(50)"
}, {
"capitalName": "Time",
"columnType": "STRING",
"comment": "数据发布时间",
"convert": false,
"keyFlag": false,
"keyIdentityFlag": false,
"name": "time",
"propertyName": "time",
"propertyType": "String",
"type": "varchar(50)"
}, {
"capitalName": "Info",
"columnType": "STRING",
"comment": "空气质量数据列表",
"convert": false,
"keyFlag": false,
"keyIdentityFlag": false,
"name": "info",
"propertyName": "info",
"propertyType": "String",
"type": "varchar(50)"
}, {
"capitalName": "Devid",
"columnType": "STRING",
"comment": "测点编号",
"convert": false,
"keyFlag": false,
"keyIdentityFlag": false,
"name": "devid",
"propertyName": "devid",
"propertyType": "String",
"type": "varchar(50)"
}, {
"capitalName": "Stationname",
"columnType": "STRING",
"comment": "测点名称",
"convert": false,
"keyFlag": false,
"keyIdentityFlag": false,
"name": "stationname",
"propertyName": "stationname",
"propertyType": "String",
"type": "varchar(50)"
}, {
"capitalName": "Aqi",
"columnType": "STRING",
"comment": "空气质量指数",
"convert": false,
"keyFlag": false,
"keyIdentityFlag": false,
"name": "aqi",
"propertyName": "aqi",
"propertyType": "String",
"type": "varchar(50)"
}, {
"capitalName": "Pm25",
"columnType": "STRING",
"comment": "pm2.5值(μg/m³)",
"convert": false,
"keyFlag": false,
"keyIdentityFlag": false,
"name": "pm25",
"propertyName": "pm25",
"propertyType": "String",
"type": "varchar(50)"
}, {
"capitalName": "Pm10",
"columnType": "STRING",
"comment": "pm10值(μg/m³)",
"convert": false,
"keyFlag": false,
"keyIdentityFlag": false,
"name": "pm10",
"propertyName": "pm10",
"propertyType": "String",
"type": "varchar(50)"
}, {
"capitalName": "Co",
"columnType": "STRING",
"comment": "一氧化碳值(mg/m³)",
"convert": false,
"keyFlag": false,
"keyIdentityFlag": false,
"name": "co",
"propertyName": "co",
"propertyType": "String",
"type": "varchar(50)"
}, {
"capitalName": "So2",
"columnType": "STRING",
"comment": "二氧化硫值(μg/m³)",
"convert": false,
"keyFlag": false,
"keyIdentityFlag": false,
"name": "so2",
"propertyName": "so2",
"propertyType": "String",
"type": "varchar(50)"
}, {
"capitalName": "No2",
"columnType": "STRING",
"comment": "二氧化氮值(μg/m³)",
"convert": false,
"keyFlag": false,
"keyIdentityFlag": false,
"name": "no2",
"propertyName": "no2",
"propertyType": "String",
"type": "varchar(50)"
}, {
"capitalName": "O3",
"columnType": "STRING",
"comment": "臭氧值(μg/m³)",
"convert": false,
"keyFlag": false,
"keyIdentityFlag": false,
"name": "o3",
"propertyName": "o3",
"propertyType": "String",
"type": "varchar(50)"
}, {
"capitalName": "Prkey",
"columnType": "STRING",
"comment": "首要污染物",
"convert": false,
"keyFlag": false,
"keyIdentityFlag": false,
"name": "prkey",
"propertyName": "prkey",
"propertyType": "String",
"type": "varchar(50)"
}],
"importPackages": ["com.baomidou.mybatisplus.annotation.IdType", "com.baomidou.mybatisplus.extension.activerecord.Model", "com.baomidou.mybatisplus.annotation.TableId", "java.io.Serializable"],
"mapperName": "AirStatLiveDataMapper",
"name": "air_stat_live_data",
"serviceImplName": "AirStatLiveDataServiceImpl",
"serviceName": "AirStatLiveDataService",
"xmlName": "AirStatLiveDataMapper"
},
"package": {
"Entity": "com.enso.entity",
"Mapper": "com.enso.mapper",
"Xml": "com.enso.mapper",
"ServiceImpl": "com.enso.service.impl",
"Service": "com.enso.service",
"Controller": "com.enso.controller"
},
"author": "Mr.Wang",
"swagger2": false,
"baseColumnList": false,
"kotlin": false,
"entityLombokModel": false,
"superMapperClassPackage": "com.baomidou.mybatisplus.core.mapper.BaseMapper",
"restControllerStyle": false,
"entityBuilderModel": true,
"superServiceClassPackage": "com.baomidou.mybatisplus.extension.service.IService",
"entityBooleanColumnRemoveIsPrefix": false,
"entityColumnConstant": false,
"config": {
"globalConfig": {
"activeRecord": true,
"author": "Mr.Wang",
"baseColumnList": false,
"baseResultMap": true,
"controllerName": "%sController",
"dateType": "TIME_PACK",
"enableCache": false,
"fileOverride": false,
"kotlin": false,
"mapperName": "%sMapper",
"open": false,
"outputDir": "C:\\Users\\Administrator\\IdeaProjects\\nan-ning\\src\\main\\java",
"serviceImplName": "%sServiceImpl",
"serviceName": "%sService",
"swagger2": false,
"xmlName": "%sMapper"
},
"packageInfo": {
"$ref": "$.package"
},
"pathInfo": {
"entity_path": "C:\\Users\\Administrator\\IdeaProjects\\nan-ning\\src\\main\\java\\com\\enso\\entity",
"controller_path": "C:\\Users\\Administrator\\IdeaProjects\\nan-ning\\src\\main\\java\\com\\enso\\controller",
"xml_path": "C:\\Users\\Administrator\\IdeaProjects\\nan-ning\\src\\main\\java\\com\\enso\\mapper",
"service_path": "C:\\Users\\Administrator\\IdeaProjects\\nan-ning\\src\\main\\java\\com\\enso\\service",
"mapper_path": "C:\\Users\\Administrator\\IdeaProjects\\nan-ning\\src\\main\\java\\com\\enso\\mapper",
"service_impl_path": "C:\\Users\\Administrator\\IdeaProjects\\nan-ning\\src\\main\\java\\com\\enso\\service\\impl"
},
"strategyConfig": {
"capitalMode": false,
"columnNaming": "underline_to_camel",
"controllerMappingHyphenStyle": false,
"entityBooleanColumnRemoveIsPrefix": false,
"entityBuilderModel": true,
"entityColumnConstant": false,
"entityLombokModel": false,
"entityTableFieldAnnotationEnable": false,
"include": ["air_stat_live_data"],
"naming": "underline_to_camel",
"restControllerStyle": false,
"skipView": false,
"superMapperClass": "com.baomidou.mybatisplus.core.mapper.BaseMapper",
"superServiceClass": "com.baomidou.mybatisplus.extension.service.IService",
"superServiceImplClass": "com.baomidou.mybatisplus.extension.service.impl.ServiceImpl"
},
"superMapperClass": "com.baomidou.mybatisplus.core.mapper.BaseMapper",
"superServiceClass": "com.baomidou.mybatisplus.extension.service.IService",
"superServiceImplClass": "com.baomidou.mybatisplus.extension.service.impl.ServiceImpl",
"tableInfoList": [{
"$ref": "$.table"
}],
"template": {
"controller": "/templates/controller.java",
"mapper": "/templates/mapper.java",
"service": "/templates/service.java",
"serviceImpl": "/templates/serviceImpl.java",
"xml": "/templates/mapper.xml"
}
},
"enableCache": false,
"entity": "AirStatLiveData"
}
3. 编写代码生成模板
鼓励大家自己写模板,别人的模板会有个人习惯。这里给出我自己的模板。
- Controller #Controller.java.ftl
package ${package.Controller};
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import top.shellfish.common.api.vo.R;
import top.shellfish.common.system.base.ExcelSupportController;
import top.shellfish.common.utils.QueryGenerator;
import ${package.Service}.${table.serviceName};
import ${package.Entity}.${entity};
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
/**
* @Description: ${table.comment} 控制层
* @Author: Shell Fish
* @Date: ${.now?string["yyyy-MM-dd"]}
* @Version: V1.0
*/
@Slf4j
@Api(tags="${table.comment}")
@RestController
@RequestMapping("/${entity?uncap_first}")
public class ${entity}Controller extends ExcelSupportController<${entity}, I${entity}Service> {
@Resource
private ${table.serviceName} ${entity?uncap_first}Service;
/**
* 分页列表查询
*
* @param ${entity?uncap_first}
* @param pageNo
* @param pageSize
* @param req
* @return
*/
@ApiOperation(value="${table.comment}-分页列表查询", notes="${table.comment}-分页列表查询")
@GetMapping(value = "/list")
public R<?> queryPageList(${entity} ${entity?uncap_first},
@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
HttpServletRequest req) {
QueryWrapper<${entity}> queryWrapper = QueryGenerator.initQueryWrapper(${entity?uncap_first}, req.getParameterMap());
Page<${entity}> page = new Page<${entity}>(pageNo, pageSize);
IPage<${entity}> pageList = ${entity?uncap_first}Service.page(page, queryWrapper);
return R.ok(pageList);
}
/**
* 添加
*
* @param ${entity?uncap_first}
* @return
*/
@ApiOperation(value="${table.comment}-添加", notes="${table.comment}-添加")
@PostMapping(value = "/add")
public R<?> add(@RequestBody ${entity} ${entity?uncap_first}) {
${entity?uncap_first}Service.save(${entity?uncap_first});
return R.ok("添加成功!");
}
/**
* 编辑
*
* @param ${entity?uncap_first}
* @return
*/
@ApiOperation(value="${table.comment}-编辑", notes="${table.comment}-编辑")
@PutMapping(value = "/edit")
public R<?> edit(@RequestBody ${entity} ${entity?uncap_first}) {
${entity?uncap_first}Service.updateById(${entity?uncap_first});
return R.ok("编辑成功!");
}
/**
* 通过id删除
*
* @param id
* @return
*/
@ApiOperation(value="${table.comment}-通过id删除", notes="${table.comment}-通过id删除")
@DeleteMapping(value = "/delete")
public R<?> delete(@RequestParam(name="id",required=true) String id) {
${entity?uncap_first}Service.removeById(id);
return R.ok("删除成功!");
}
/**
* 批量删除
*
* @param ids
* @return
*/
@ApiOperation(value="${table.comment}-批量删除", notes="${table.comment}-批量删除")
@DeleteMapping(value = "/deleteBatch")
public R<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
this.${entity?uncap_first}Service.removeByIds(Arrays.asList(ids.split(",")));
return R.ok("批量删除成功!");
}
/**
* 通过id查询
*
* @param id
* @return
*/
@ApiOperation(value="${table.comment}-通过id查询", notes="${table.comment}-通过id查询")
@GetMapping(value = "/queryById")
public R<?> queryById(@RequestParam(name="id",required=true) String id) {
${entity} ${entity?uncap_first} = ${entity?uncap_first}Service.getById(id);
if(${entity?uncap_first}==null) {
return R.error("未找到对应数据");
}
return R.ok(${entity?uncap_first});
}
/**
* 导出excel
*
* @param request
* @param ${entity?uncap_first}
*/
@RequestMapping(value = "/exportXls")
public void exportXls(HttpServletRequest request, HttpServletResponse response, ${entity} ${entity?uncap_first}) {
try {
super.exportXls(request, response, ${entity?uncap_first}, ${entity}.class, "${table.comment}");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 通过excel导入数据
*
* @param request
* @param response
* @return
*/
@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
public R<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
return super.importExcel(request, response, ${entity}.class);
}
}
- Entity #Entity.java.ftl
package ${package.Entity};
import com.baomidou.mybatisplus.annotation.*;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Builder;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import org.jeecgframework.poi.excel.annotation.Excel;
import org.springframework.format.annotation.DateTimeFormat;
import java.io.Serializable;
import java.util.Date;
/**
* @Description: ${table.comment} 实体
* @Author: Shell Fish
* @Date: ${.now?string["yyyy-MM-dd"]}
* @Version: V1.0
*/
@Data
@Builder
@TableName("${table.name}")
@Accessors(chain = true)
@EqualsAndHashCode(callSuper = false)
@ApiModel(value="${table.name}对象", description="${table.comment}")
public class ${entity} implements Serializable {
private static final long serialVersionUID = 1L;
<#list table.fields as field>
/**
* ${field.comment}
*/
<#if field.propertyName == 'createdTime'>
@TableField(fill = FieldFill.INSERT)
</#if>
<#if field.propertyName == 'updatedTime'>
@TableField(fill = FieldFill.INSERT_UPDATE)
</#if>
<#if field.keyIdentityFlag>
@TableId(type = IdType.ASSIGN_ID)
</#if>
@ApiModelProperty(value = "${field.comment}", example = "")
<#if field.type =='date'>
@Excel(name = "${field.comment}", width = 15, format = "yyyy-MM-dd")
@DateTimeFormat(pattern="yyyy-MM-dd")
@JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd")
</#if>
<#if field.type =='datetime'>
@Excel(name = "${field.comment}", width = 15, format = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
@JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd HH:mm:ss")
</#if>
private ${field.propertyType} ${field.propertyName};
</#list>
}
- Service #Service.java.ftl
package ${package.Service};
import ${package.Entity}.${entity};
import com.baomidou.mybatisplus.extension.service.IService;
/**
* @Description: ${table.comment} 业务接口
* @Author: Shell Fish
* @Date: ${.now?string["yyyy-MM-dd"]}
* @Version: V1.0
*/
public interface ${table.serviceName} extends ${superServiceClass}<${entity}> {
}
- ServiceImpl #ServiceImpl.java.ftl
package ${package.ServiceImpl};
import ${package.Entity}.${entity};
import ${package.Mapper}.${table.mapperName};
import ${package.Service}.${table.serviceName};
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
/**
* @Description: ${table.comment} 业务层
* @Author: Shell Fish
* @Date: ${.now?string["yyyy-MM-dd"]}
* @Version: V1.0
*/
@Service
public class ${table.serviceImplName} extends ${superServiceImplClass}<${table.mapperName}, ${entity}> implements ${table.serviceName} {
}
- Mappper #Mapper.java.ftl
package ${package.Mapper};
import ${package.Entity}.${entity};
import ${superMapperClassPackage};
/**
* @Description: ${table.comment} Mapper 接口
* @Author: Shell Fish
* @Date: ${.now?string["yyyy-MM-dd"]}
* @Version: V1.0
*/
public interface ${table.mapperName} extends BaseMapper<${entity}> {
}
- Xml #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}">
</mapper>
4. 代码生成器工具类
package top.shellfish.common.utils;
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.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import org.apache.commons.lang3.StringUtils;
import java.util.*;
// 演示例子,执行 main 方法控制台输入模块表名回车自动生成对应项目目录中
public class CodeGenerator {
//数据源配置
static String url = "jdbc:mysql://127.0.0.1:3306/road_trip?characterEncoding=UTF-8&useUnicode=true&useSSL=false&tinyInt1isBit=false&allowPublicKeyRetrieval=true&serverTimezone=Asia/Shanghai";
static String username = "root";
static String password = "123456";
//static String driverName = "com.mysql.jdbc.Driver";
static String driverName = "com.mysql.cj.jdbc.Driver";
//包配置
static String moduleName = "module";
static String parent = "top.shellfish";
/** 父包名路径(文件输出路径,也是导包的路径) */
private static String PARENT_PACKAGE_PATH = "/top/shellfish";
// 各层包名
private static String ENTITY_PATH = "/entity/";
private static String MAPPER_PATH = "/mapper/";
private static String XML_PATH = "/mapper/xml/";
private static String SERVICE_PATH = "/service/";
private static String SERVICE_IMPL_PATH = "/service/impl/";
private static String CONTROLLER_PATH = "/controller/";
/**项目目录*/
private static String PROJECT_PATH = System.getProperty("user.dir");
/**模块名*/
private static String MODULE_NAME = "/module";
/** entity输出模板 */
private static String ENTITY_TEMPLATE = "templates/entity/Entity.java.ftl";
private static String ENTITY_OUTPUT_PATH = PROJECT_PATH + "/src/main/java/top/shellfish" + MODULE_NAME + "/entity/";
/** mapper.xml输出模板 */
private static String XML_TEMPLATE = "templates/mapper/xml/Mapper.xml.ftl";
private static String XML_OUTPUT_PATH = PROJECT_PATH + "/src/main/java/top/shellfish/" + MODULE_NAME + "/mapper/xml/";
/** mapper.java输出模板 */
private static String MAPPER_TEMPLATE = "templates/mapper/Mapper.java.ftl";
private static String MAPPER_OUTPUT_PATH = PROJECT_PATH + "/src/main/java/top/shellfish/" + MODULE_NAME + "/mapper/";
/** service输出模板 */
private static String SERVICE_TEMPLATE = "templates/service/Service.java.ftl";
private static String SERVICE_OUTPUT_PATH = PROJECT_PATH + "/src/main/java/top/shellfish/" + MODULE_NAME + "/service/";
/** serviceImpl输出模板 */
private static String SERVICE_IMPL_TEMPLATE = "templates/service/impl/ServiceImpl.java.ftl";
private static String SERVICE_IMPL_OUTPUT_PATH = PROJECT_PATH + "/src/main/java/top/shellfish/" + MODULE_NAME + "/service/impl/";
/** controller输出模板 */
private static String CONTROLLER_TEMPLATE = "templates/controller/Controller.java.ftl";
private static String CONTROLLER_OUTPUT_PATH = PROJECT_PATH + "/src/main/java/top/shellfish/" + MODULE_NAME + "/controller/";
public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 设置模板引擎 Freemarker
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
// 设置全局配置
mpg.setGlobalConfig(globalConfig());
// 数据源配置
mpg.setDataSource(dataSourceConfig());
// 包配置
mpg.setPackageInfo(packageConfig());
// 注入配置
mpg.setCfg(injectionConfig());
// 配置模板
mpg.setTemplate(templateConfig());
// 策略配置
mpg.setStrategy(strategyConfig());
//生成
mpg.execute();
}
/**
* <p>
* 读取控制台内容
* </p>
*/
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.isNotBlank(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("请输入正确的" + tip + "!");
}
public static GlobalConfig globalConfig(){
GlobalConfig gc = new GlobalConfig();
gc.setOutputDir(System.getProperty("user.dir")+ "/src/main/java");
gc.setAuthor("Shell Fish");
gc.setOpen(false);
gc.setFileOverride(true);
// gc.setSwagger2(true); 实体属性 Swagger2 注解
return gc;
}
public static DataSourceConfig dataSourceConfig(){
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl(url);
// dsc.setSchemaName("public");
dsc.setDriverName(driverName);
dsc.setUsername(username);
dsc.setPassword(password);
return dsc;
}
public static PackageConfig packageConfig(){
PackageConfig pc = new PackageConfig();
pc.setModuleName(moduleName);
pc.setParent(parent);
return pc;
}
public static TemplateConfig templateConfig(){
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
// 配置自定义输出模板
//指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
templateConfig.setEntity(null);
templateConfig.setService(null);
templateConfig.setController(null);
templateConfig.setMapper(null);
templateConfig.setXml(null);
templateConfig.setServiceImpl(null);
return templateConfig;
}
private static InjectionConfig injectionConfig() {
return new InjectionConfig() {
@Override
public void initMap() {
// 注入配置
Map<String, Object> map = new HashMap<>();
this.setMap(map);
}
}.setFileOutConfigList(fileOutConfigList());
}
private static List<FileOutConfig> fileOutConfigList() {
List<FileOutConfig> list = new ArrayList<>();
// 实体类文件输出
list.add(new FileOutConfig(ENTITY_TEMPLATE) {
@Override
public String outputFile(TableInfo tableInfo) {
return ENTITY_OUTPUT_PATH + tableInfo.getEntityName() + StringPool.DOT_JAVA;
}
});
// mapper xml文件输出
list.add(new FileOutConfig(XML_TEMPLATE) {
@Override
public String outputFile(TableInfo tableInfo) {
return XML_OUTPUT_PATH + tableInfo.getMapperName() + StringPool.DOT_XML;
}
});
// mapper文件输出
list.add(new FileOutConfig(MAPPER_TEMPLATE) {
@Override
public String outputFile(TableInfo tableInfo) {
return MAPPER_OUTPUT_PATH + tableInfo.getMapperName() + StringPool.DOT_JAVA;
}
});
// service文件输出
list.add(new FileOutConfig(SERVICE_TEMPLATE) {
@Override
public String outputFile(TableInfo tableInfo) {
return SERVICE_OUTPUT_PATH + tableInfo.getServiceName() + StringPool.DOT_JAVA;
}
});
// service impl文件输出
list.add(new FileOutConfig(SERVICE_IMPL_TEMPLATE) {
@Override
public String outputFile(TableInfo tableInfo) {
return SERVICE_IMPL_OUTPUT_PATH + tableInfo.getServiceImplName() + StringPool.DOT_JAVA;
}
});
// controller文件输出
list.add(new FileOutConfig(CONTROLLER_TEMPLATE) {
@Override
public String outputFile(TableInfo tableInfo) {
return CONTROLLER_OUTPUT_PATH + tableInfo.getControllerName() + StringPool.DOT_JAVA;
}
});
return list;
}
private static StrategyConfig strategyConfig() {
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
// strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!");
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
// 公共父类
// strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");
// 写于父类中的公共字段
// strategy.setSuperEntityColumns("id");
strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
strategy.setControllerMappingHyphenStyle(true);
// strategy.setTablePrefix(pc.getModuleName() + "_");
return strategy;
}
}

浙公网安备 33010602011771号