上次使用generator生成了无逻辑代码,并且有service接口和实现类的文件,这次我对模板文件进行改良,修改了生成文件类型,满足mybatisplus框架,废话不多说,上码!!
首先对模板文件进行修改
再resource目录下新建templates目录
在templates目录下新建freemarker模板
这里有人要问了,mybatisplus不是集成了crud了嘛,可以不用xml文件了呀,我只能说稍微做的项目出现复杂查询或复杂分页等等的,还是要自写xml的啦
controller模板
package ${package.Controller};
import ${package.Service}.${entity}Service;
import ${package.Entity}.${entity};
import com.auto.system.utils.dataResponse.DataResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.auto.system.utils.dataResponse.responseenum.BizSuccessEnum;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/${table.entityPath}" )
public class ${entity}Controller {
@Autowired
public ${entity}Service ${table.entityPath}Service;
/**
* 分页查询
* @param params
* @return
*/
@PostMapping("/selectByPage")
public DataResponse selectByPage(@RequestBody Map<String, Object> params) {
Page<Map<String, Object>> pageList = this.${table.entityPath}Service.selectByPage(params);
return new DataResponse().defaultOperationResponse(BizSuccessEnum.BUSINESS_QUERY_SUCCESS.getMessage(), pageList);
}
/**
* 新增
* @param params
* @return
*/
@PostMapping("/add${entity}")
public DataResponse add${entity}(@RequestBody Map<String, Object> params) {
DataResponse dataResponse = this.${table.entityPath}Service.add${entity}(params);
return dataResponse;
}
/**
* 删除
* @param params
* @return
*/
@PostMapping("/del${entity}")
public DataResponse del${entity}(@RequestBody Map<String, Object> params) {
DataResponse dataResponse = this.${table.entityPath}Service.del${entity}(params);
return dataResponse;
}
/**
*更新
* @param params
* @return
*/
@PostMapping("/update${entity}")
public DataResponse update${entity}(@RequestBody Map<String, Object> params) {
DataResponse dataResponse = this.${table.entityPath}Service.update${entity}(params);
return dataResponse;
}
}
entity模板
package ${package.Entity};
<#list table.importPackages as pkg>
import ${pkg};
</#list>
<#if swagger2>
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
</#if>
<#if entityLombokModel>
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
</#if>
/**
*
* ${table.comment!}
*
*
* @author ${author}
* @since ${date}
*/
<#if entityLombokModel>
@Data
<#if superEntityClass??>
@EqualsAndHashCode(callSuper = true)
<#else>
@EqualsAndHashCode(callSuper = false)
</#if>
@Accessors(chain = true)
</#if>
<#if table.convert>
@TableName("${table.name}")
</#if>
<#if swagger2>
@ApiModel(value="${entity}对象", description="${table.comment!}")
</#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>
<#if entitySerialVersionUID>
private static final long serialVersionUID = 1L;
</#if>
<#-- ---------- BEGIN 字段循环遍历 ---------->
<#list table.fields as field>
<#if field.keyFlag>
<#assign keyPropertyName="${field.propertyName}"/>
</#if>
<#if field.comment!?length gt 0>
<#if swagger2>
@ApiModelProperty(value = "${field.comment}")
<#else>
/**
* ${field.comment}
*/
</#if>
</#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模板
package ${package.Mapper};
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import ${package.Entity}.${entity};
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Component;
import java.util.Map;
/**
*
* $!{table.comment} Mapper 接口
*
*
* @author ${author}
* @since ${date}
*/
@Component
public interface ${entity}Mapper extends BaseMapper<${entity}>{
Page<Map<String,Object>> selectByPage(@Param("page") Page page,@Param("params") Map<String,Object> params);
}
这里我自写了一个分页
xml模板
<mapper namespace="${package.Mapper}.${table.mapperName}">
<resultMap id="BaseResultMap" type="${package.Entity}.${entity}">
<#list table.fields as field>
<result column="${field.name}" property="${field.propertyName}" />
#list>
resultMap>
<sql id="Base_Column_List">
<#list table.commonFields as field>
${field.name},
#list>
${table.fieldNames}
sql>
<select id="selectByPage" resultType="java.util.Map">
select
<include refid="Base_Column_List"/>
from ${table.name}
<where>
<#list table.fields as field>
<#if field.keyFlag ><#--生成主键排在第一位-->
<if test="params.${field.propertyName} != null and params.${field.propertyName} != ''" >
${field.propertyName} = # {params.${field.name}}
if>
#if>
#list>
<#list table.fields as field>
<#if !field.keyFlag >##生成普通字段
<if test="params.${field.propertyName} != null and params.${field.propertyName} != ''">
and ${field.propertyName} = # {params.${field.name}}
if>
#if>
#list>
where>
select>
mapper>
service模板
package ${package.Service};
import ${package.Entity}.${entity};
import ${package.Mapper}.${entity}Mapper;
import com.auto.system.utils.factory.PageFactory;
import com.auto.system.utils.dataResponse.DataResponse;
import com.auto.system.utils.dataResponse.responseenum.BizSuccessEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import java.util.Map;
import com.alibaba.fastjson.JSON;
/**
*
* ${table.comment!} 服务类
*
*
* @author ${author}
* @since ${date}
*/
@Service
@Transactional(rollbackFor = Exception.class)
public class ${entity}Service extends ServiceImpl< ${entity}Mapper,${entity}>{
@Autowired
private ${table.mapperName} ${table.entityPath}Mapper;
/**
* 分页显查询
*
* @param params
* @return
*/
public Page< Map< String, Object>> selectByPage(Map< String, Object> params) {
Page page = PageFactory.defaultPage(params);
Page< Map< String, Object>> pageList = this.${table.entityPath}Mapper.selectByPage(page, params);
return pageList;
}
/**
* 新增
*
* @param params
* @return
*/
public DataResponse add${entity}(Map< String, Object> params) {
${entity} ${table.entityPath} = JSON.parseObject(JSON.toJSONString(params), ${entity}.class);
this.${table.entityPath}Mapper.insert(${table.entityPath});
return new DataResponse().defaultOperationResponse(BizSuccessEnum.BUSINESS_INSERT_SUCCESS.getMessage());
}
/**
* 删除问题
*
* @param params
* @return
*/
public DataResponse del${entity}(Map< String, Object> params) {
Integer ${table.entityPath}Id = (Integer) params.get("${table.entityPath}");
this.${table.entityPath}Mapper.deleteById(${table.entityPath}Id);
return new DataResponse().defaultOperationResponse(BizSuccessEnum.BUSINESS_DELETE_SUCCESS.getMessage());
}
/**
* 更新
* @param params
* @return
*/
public DataResponse update${entity}(Map< String, Object> params){
${entity} ${table.entityPath} = JSON.parseObject(JSON.toJSONString(params), ${entity}.class);
this.${table.entityPath}Mapper.updateById(${table.entityPath});
return new DataResponse().defaultOperationResponse(BizSuccessEnum.BUSINESS_OPERATE_SUCCESS.getMessage());
}
}
模板建立完毕,使用我们的代码生成器类,之前也放过,但是做了部分修改
GenMainUtil类
package com.auto.system.utils;
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 java.util.ArrayList;
import java.util.List;
/**
* @author FlyYant
* @date 2021/3/24
* 代码生成类
*
* demo
* 表名
*/
public class GenMainUtil {
/**
*
* 读取控制台内容
*
*/
public static void genMain(String tableName){
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor("flyyant");
gc.setOpen(true);
// gc.setSwagger2(true); 实体属性 Swagger2 注解
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
// Oracle路径
// dsc.setUrl("jdbc:oracle:thin:@localhost:1521:orcl");
dsc.setUrl("jdbc:mysql://localhost:3306/auto_system?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC");
// dsc.setSchemaName("public");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("123456");
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName("system");
pc.setParent("com.auto");
mpg.setPackageInfo(pc);
// 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
// 如果模板引擎是 freemarker
// String templatePath = "/templates/mapper.xml.ftl";
// 如果模板引擎是 velocity
// String templatePath = "/templates/mapper.xml.vm";
// 自定义输出配置
List<FileOutConfig> focList = new ArrayList<>();
// 自定义配置会被优先输出
focList.add(new FileOutConfig("/templates/controller.java.ftl") {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
return projectPath + "/src/main/java/com/auto/" + pc.getModuleName()
+ "/" + "controller/" + tableInfo.getEntityName() + "Controller" + StringPool.DOT_JAVA;
}
});
focList.add(new FileOutConfig("/templates/entity.java.ftl") {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
return projectPath + "/src/main/java/com/auto/" + pc.getModuleName()
+ "/" + "entity/" + tableInfo.getEntityName() + StringPool.DOT_JAVA;
}
});
focList.add(new FileOutConfig("/templates/mapper.java.ftl") {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
return projectPath + "/src/main/java/com/auto/" + pc.getModuleName()
+ "/" + "mapper/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_JAVA;
}
});
focList.add(new FileOutConfig("/templates/service.java.ftl") {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
return projectPath + "/src/main/java/com/auto/" + pc.getModuleName()
+ "/" + "service/" + tableInfo.getEntityName() + "Service" + StringPool.DOT_JAVA;
}
});
focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
return projectPath + "/src/main/java/com/auto/" + pc.getModuleName()
+ "/" + "mapper/mapping/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
System.out.println(focList);
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
//将generator自带的模板设置为空意为不生成该模板文件
templateConfig.setXml(null);
templateConfig.setServiceImpl(null);
templateConfig.setEntityKt(null);
templateConfig.setService(null);
mpg.setTemplate(templateConfig);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
// 公共父类
// strategy.setSuperControllerClass("com.baomidou.ant.common.BaseController");
// 写于父类中的公共字段
strategy.setSuperEntityColumns("id");
strategy.setInclude(tableName);
strategy.setSuperServiceClass(null);
strategy.setControllerMappingHyphenStyle(true);
strategy.setTablePrefix(pc.getModuleName() + "_");
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
public static void genMainFace(String tableName) {
// 代码生成器
genMain(tableName);
}
public static void main(String[] args){
genMain("acb");
}
}
需要手动输入的 写一个scanner就行了,需要调用的,直接外部调用genMainFace方法就可以了
运行!!!!!
生成了如下文件
数据库随便瞎搞得,只为了测试
生成的controller文件
AcbController
package com.auto.system.controller;
import com.auto.system.service.AcbService;
import com.auto.system.entity.Acb;
import com.auto.system.utils.dataResponse.DataResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.auto.system.utils.dataResponse.responseenum.BizSuccessEnum;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/acb" )
public class AcbController {
@Autowired
public AcbService acbService;
/**
* 分页查询
* @param params
* @return
*/
@PostMapping("/selectByPage")
public DataResponse selectByPage(@RequestBody Map<String, Object> params) {
Page<Map<String, Object>> pageList = this.acbService.selectByPage(params);
return new DataResponse().defaultOperationResponse(BizSuccessEnum.BUSINESS_QUERY_SUCCESS.getMessage(), pageList);
}
/**
* 新增
* @param params
* @return
*/
@PostMapping("/addAcb")
public DataResponse addAcb(@RequestBody Map<String, Object> params) {
DataResponse dataResponse = this.acbService.addAcb(params);
return dataResponse;
}
/**
* 删除
* @param params
* @return
*/
@PostMapping("/delAcb")
public DataResponse delAcb(@RequestBody Map<String, Object> params) {
DataResponse dataResponse = this.acbService.delAcb(params);
return dataResponse;
}
/**
*更新
* @param params
* @return
*/
@PostMapping("/updateAcb")
public DataResponse updateAcb(@RequestBody Map<String, Object> params) {
DataResponse dataResponse = this.acbService.updateAcb(params);
return dataResponse;
}
}
entity文件
Acb
package com.auto.system.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import java.io.Serializable;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
/**
*
*
*
*
* @author flyyant
* @since 2021-04-12
*/
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class Acb implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "acb_id", type = IdType.AUTO)
private Integer acbId;
private String apple;
private String what;
private String pace;
private String acbName;
}
xml文件
AcbMapper.xml
<mapper namespace="com.auto.system.mapper.AcbMapper">
<resultMap id="BaseResultMap" type="com.auto.system.entity.Acb">
<result column="acb_id" property="acbId" />
<result column="apple" property="apple" />
<result column="what" property="what" />
<result column="pace" property="pace" />
<result column="acb_name" property="acbName" />
resultMap>
<sql id="Base_Column_List">
acb_id, apple, what, pace, acb_name
sql>
<select id="selectByPage" resultType="java.util.Map">
select
<include refid="Base_Column_List"/>
from acb
<where>
<if test="params.acbId != null and params.acbId != ''" >
acbId = # {params.acb_id}
if>
##生成普通字段
<if test="params.apple != null and params.apple != ''">
and apple = # {params.apple}
if>
##生成普通字段
<if test="params.what != null and params.what != ''">
and what = # {params.what}
if>
##生成普通字段
<if test="params.pace != null and params.pace != ''">
and pace = # {params.pace}
if>
##生成普通字段
<if test="params.acbName != null and params.acbName != ''">
and acbName = # {params.acb_name}
if>
where>
select>
mapper>
mapper文件
AcbMapper
package com.auto.system.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.auto.system.entity.Acb;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Component;
import java.util.Map;
/**
*
* $!{table.comment} Mapper 接口
*
*
* @author flyyant
* @since 2021-04-12
*/
@Component
public interface AcbMapper extends BaseMapper<Acb>{
Page<Map<String,Object>> selectByPage(@Param("page") Page page,@Param("params") Map<String,Object> params);
}
service文件
AcbService
package com.auto.system.service;
import com.auto.system.entity.Acb;
import com.auto.system.mapper.AcbMapper;
import com.auto.system.utils.factory.PageFactory;
import com.auto.system.utils.dataResponse.DataResponse;
import com.auto.system.utils.dataResponse.responseenum.BizSuccessEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import java.util.Map;
import com.alibaba.fastjson.JSON;
/**
*
* 服务类
*
*
* @author flyyant
* @since 2021-04-12
*/
@Service
@Transactional(rollbackFor = Exception.class)
public class AcbService extends ServiceImpl< AcbMapper,Acb>{
@Autowired
private AcbMapper acbMapper;
/**
* 分页显查询
*
* @param params
* @return
*/
public Page< Map< String, Object>> selectByPage(Map< String, Object> params) {
Page page = PageFactory.defaultPage(params);
Page< Map< String, Object>> pageList = this.acbMapper.selectByPage(page, params);
return pageList;
}
/**
* 新增
*
* @param params
* @return
*/
public DataResponse addAcb(Map< String, Object> params) {
Acb acb = JSON.parseObject(JSON.toJSONString(params), Acb.class);
this.acbMapper.insert(acb);
return new DataResponse().defaultOperationResponse(BizSuccessEnum.BUSINESS_INSERT_SUCCESS.getMessage());
}
/**
* 删除问题
*
* @param params
* @return
*/
public DataResponse delAcb(Map< String, Object> params) {
Integer acbId = (Integer) params.get("acb");
this.acbMapper.deleteById(acbId);
return new DataResponse().defaultOperationResponse(BizSuccessEnum.BUSINESS_DELETE_SUCCESS.getMessage());
}
/**
* 更新
* @param params
* @return
*/
public DataResponse updateAcb(Map< String, Object> params){
Acb acb = JSON.parseObject(JSON.toJSONString(params), Acb.class);
this.acbMapper.updateById(acb);
return new DataResponse().defaultOperationResponse(BizSuccessEnum.BUSINESS_OPERATE_SUCCESS.getMessage());
}
}
需要自定义想生成什么样子的逻辑代码,都可以直接自在对应模板内改动
忘记说了mybatisplus和mybatisplus-generator的依赖包不要忘记导入哦
<!--mybatis-plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.1.1</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.3.0</version>
</dependency>
我是飞扬,专注于写bug的程序猿