Mybatis-plus自定义业务模版代码生成器

1 pom引入依赖


    
      com.baomidou
      mybatis-plus-generator
      3.3.2
    
    
      com.baomidou
      mybatisplus-spring-boot-starter
      1.0.3
    
    
    
      com.baomidou
      mybatis-plus
      3.0.5
    
    
    
      org.apache.velocity
      velocity-engine-core
      2.2
    

2 生成代码工具类

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;

import java.util.HashMap;
import java.util.Map;

public class GeneratorUtil {
    /**
     * 

* MySQL 生成演示 *

*/
public static void main(String[] args) { AutoGenerator mpg = new AutoGenerator(); // 选择 freemarker 引擎,默认 Veloctiy // mpg.setTemplateEngine(new FreemarkerTemplateEngine()); // 全局配置 GlobalConfig gc = new GlobalConfig(); gc.setOutputDir("代码生成目的路径"); gc.setFileOverride(true); gc.setActiveRecord(true);// 不需要ActiveRecord特性的请改为false gc.setEnableCache(false);// XML 二级缓存 gc.setBaseResultMap(true);// XML ResultMap gc.setBaseColumnList(true);// XML columList //gc.setKotlin(true);//是否生成 kotlin 代码 gc.setAuthor("作者"); // 自定义文件命名,注意 %s 会自动填充表实体属性! gc.setMapperName("%sDao"); // gc.setXmlName("%sDao"); gc.setServiceName("%sService"); // gc.setServiceImplName("%sServiceDiy"); // gc.setControllerName("%sAction"); // gc.setEntityName("%s"); mpg.setGlobalConfig(gc); // 数据源配置 DataSourceConfig dsc = new DataSourceConfig(); dsc.setDbType(DbType.MYSQL); dsc.setDriverName("com.mysql.cj.jdbc.Driver"); dsc.setUsername("root"); dsc.setPassword("root"); dsc.setUrl("jdbc:mysql://localhost:3306/soa_afa?userUnicode=true&characterEncoding=utf8&serverTimezone=UTC&nullCatalogMeansCurrent=true"); mpg.setDataSource(dsc); // 策略配置 StrategyConfig strategy = new StrategyConfig(); // strategy.setCapitalMode(true);// 全局大写命名 ORACLE 注意 //strategy.setTablePrefix(new String[] { "tlog_", "tsys_" });// 此处可以修改为您的表前缀 strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略 strategy.setInclude(new String[] { "soa_service" }); // 需要生成的表集合,中间用逗号分隔 // strategy.setExclude(new String[]{"test"}); // 排除生成的表 // 自定义实体父类 // strategy.setSuperEntityClass("com.baomidou.demo.TestEntity"); // 自定义实体,公共字段 // strategy.setSuperEntityColumns(new String[] { "test_id", "age" }); // 自定义 mapper 父类 strategy.setSuperMapperClass("com.tz.marlon.BaseMapper"); // 自定义 service 父类 strategy.setSuperServiceClass("com.tz.marlon.service.ExcelBaseService"); // 自定义 service 实现类父类 strategy.setSuperServiceImplClass("com.tz.marlon.service.ExcelBaseServiceImpl"); // 自定义 controller 父类 // strategy.setSuperControllerClass("com.baomidou.demo.TestController"); // 【实体】是否生成字段常量(默认 false) // public static final String ID = "test_id"; strategy.setEntityColumnConstant(true); // 【实体】是否为构建者模型(默认 false) // public User setName(String name) {this.name = name; return this;} //strategy.setEntityBuilderModel(true); strategy.setEntityLombokModel(true);//采用lomback mpg.setStrategy(strategy); // 包配置 PackageConfig pc = new PackageConfig(); pc.setParent("com.tz.marlon"); pc.setController("controller"); pc.setEntity("entity"); pc.setMapper("dao"); //@todo 模块名,访问路径会用到 pc.setModuleName("模块名"); mpg.setPackageInfo(pc); // 注入自定义配置,可以在 VM 中使用 cfg.abc 【可无】 ${cfg.abc} InjectionConfig cfg = new InjectionConfig() { @Override public void initMap() { Map<String, Object> map = new HashMap<String, Object>(); map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp"); this.setMap(map); } }; // 自定义模板配置,可以 copy 源码 mybatis-plus/src/main/resources/templates 下面内容修改, TemplateConfig tc = new TemplateConfig(); tc.setController("/templates/controller.java.vm"); tc.setService("/templates/service.java.vm"); tc.setServiceImpl("/templates/serviceImpl.java.vm"); tc.setEntity("/templates/entity.java.vm"); tc.setMapper("/templates/mapper.java.vm"); tc.setXml("/templates/mapper.xml.vm"); // 如上任何一个模块如果设置 空 OR Null 将不生成该模块。 mpg.setTemplate(tc); // 执行生成 mpg.execute(); // 打印注入设置【可无】 System.err.println(mpg.getCfg().getMap().get("abc")); } }

依赖引入了,生成代码工具类也写好了,剩下的就是根据自己的业务代码,配置自己的业务的模版。

3 模版

3.1 实体类模版 entity.java.vm

package ${package.Entity};

#if(${activeRecord})
import java.io.Serializable;

#end
#foreach($pkg in ${table.importPackages})
import ${pkg};
#end

import cn.com.agree.aweb.common.base.entity.BasePO;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import javax.persistence.*;


/**
 * 

* $!{table.comment} *

* * @author ${author} * @since ${date} */ @Data @EqualsAndHashCode() @Accessors(chain = true) @Entity @Table(name = "${table.name}") public class ${entity} extends BasePO { private static final long serialVersionUID = 1L; ## ---------- BEGIN 字段循环遍历 ---------- #foreach($field in ${table.fields}) #if(${field.keyFlag}) #set($keyPropertyName=${field.propertyName}) #end #if("$!field.comment" != "") /** * ${field.comment} */ #end #if(${field.keyFlag}) ## 主键 #if(${field.keyIdentityFlag}) @TableId(value="${field.name}", type= IdType.AUTO) #elseif(${field.convert}) @TableId("${field.name}") #end ## 普通字段 #elseif(${field.fill}) ## ----- 存在字段填充设置 ----- #if(${field.convert}) @TableField(value = "${field.name}", fill = FieldFill.${field.fill}) #else @TableField(fill = FieldFill.${field.fill}) #end #elseif(${field.convert}) @TableField("${field.name}") #end ## 乐观锁注解 #if(${versionFieldName}==${field.name}) @Version #end ## 逻辑删除注解 #if(${logicDeleteFieldName}==${field.name}) @TableLogic #end @Column(name = "${field.name}", length = 36) private ${field.propertyType} ${field.propertyName}; #end ## ---------- END 字段循环遍历 ---------- #if(!${entityLombokModel}) #foreach($field in ${table.fields}) #if(${field.propertyType.equals("boolean")}) #set($getprefix="is") #else #set($getprefix="get") #end 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}) { #end this.${field.propertyName} = ${field.propertyName}; #if(${entityBuilderModel}) return this; #end } #end #end #if(${activeRecord}) @Override protected Serializable pkVal() { #if(${keyPropertyName}) return this.${keyPropertyName}; #else return this.id; #end } #end #if(!${entityLombokModel}) @Override public String toString() { return "${entity}{" + #foreach($field in ${table.fields}) #if($!{velocityCount}==1) "${field.propertyName}=" + ${field.propertyName} + #else ", ${field.propertyName}=" + ${field.propertyName} + #end #end "}"; } #end }

3.2 dao层模版mapper.java.vm

package ${package.Mapper};

import ${package.Entity}.${entity};
import org.springframework.data.jpa.repository.support.JpaRepositoryImplementation;

/**
 * 

* $!{table.comment} Mapper 接口 *

* * @author ${author} * @since ${date} */ public interface ${table.mapperName} extends JpaRepositoryImplementation<${entity}, String> { }

3.3 service层模版service.java.vm

package ${package.Service};

import ${package.Entity}.${entity};
import ${superServiceClassPackage};

/**
 * 

* $!{table.comment} 服务类 *

* * @author ${author} * @since ${date} */ public interface ${table.serviceName} extends ${superServiceClass}<${entity},String> { }

3.4 service实现类模版serviceImpl.java.vm

package ${package.ServiceImpl};


import ${package.Entity}.${entity};
import ${package.Mapper}.${table.mapperName};
import ${package.Service}.${table.serviceName};
import ${superServiceImplClassPackage};
import org.springframework.data.jpa.repository.support.JpaRepositoryImplementation;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
/**
 * 

* $!{table.comment} 服务实现类 *

* * @author ${author} * @since ${date} */ @Service @Transactional public class ${table.serviceImplName} extends ${superServiceImplClass}<${entity}, String> implements ${table.serviceName} { @Autowired private ${table.mapperName} ${table.entityPath}Dao; @Override public JpaRepositoryImplementation<${entity}, String> getDao() { return ${table.entityPath}Dao; } @Override public Class getPOClass() { return ${entity}.class; } @Override public Class getVOClass() { return ${entity}.class; } }

3.5 controller层模版controller.java.vm

package ${package.Controller};


#if(${superControllerClassPackage})
import ${superControllerClassPackage};
#end
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.GetMapping;
import cn.com.agree.aweb.common.base.entity.RespMessage;
import cn.com.agree.aweb.entity.query.QueryEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import ${package.Service}.${table.serviceName};
import ${package.Entity}.${entity};
import java.util.List;

/**
 *
 * @author ${author}
 * @since ${date}
 */
@Api(value = "/${package.ModuleName}", description = "${table.comment}")
@Slf4j
@RestController
@RequestMapping("/${package.ModuleName}#end/#if(${controllerMappingHyphenStyle})${controllerMappingHyphen}#else${table.entityPath}#end")
#if(${superControllerClass})
public class ${table.controllerName} extends ${superControllerClass} {
#else
public class ${table.controllerName} {
#end

    ${entity}Mapper mapper = ${entity}Mapper.INSTANCE;
    @Autowired
    public ${table.serviceName} ${table.entityPath}Service;

    @RequestMapping(method= RequestMethod.GET,value = {"/queryLists"})
    public Page<${entity}VO> queryLists(@RequestBody QueryEntity<${entity}VO> queryEntity){
        return ${table.entityPath}Service.findByQuery(queryEntity);
    }

    @ApiOperation(value = "添加${table.comment}", notes = "添加${table.comment}")
    @PostMapping("/add")
    public ${entity}VO add(@RequestBody ${entity}VO vo) {
        return mapper.poToVO(${table.entityPath}Service.add(mapper.voToPO(vo)));
    }

    @ApiOperation(value = "修改${table.comment}", notes = "修改${table.comment}")
    @PostMapping("/update")
    public ${entity}VO update(@RequestBody ${entity}VO vo) {
        return mapper.poToVO(${table.entityPath}Service.update(mapper.voToPO(vo), vo.getId()));
    }

    @ApiOperation(value = "删除${table.comment}", notes = "根据id删除${table.comment}")
    @PostMapping("/delete")
    public RespMessage delete(@RequestBody List ids) {
        ${table.entityPath}Service.delete(ids);
        return RespMessage.ok();
    }

}

执行生成代码工具类之后就会生成一套自己的业务代码。

4 生成的代码还需要修改

由于业务比较繁琐,需要手工做一些修改,修改内容如下:
第一步:给实体类名后加上PO后缀
Mybatis-plus自定义业务模版代码生成器_第1张图片
第二步:复制修改后的po实体类到vo包下并修改名称及添加一些业务需要的冗余字段
第三步:在mapper包下新建一个对应模块业务的mapper

import cn.com.agree.aweb.common.base.mapper.BaseMapper;
import cn.com.agree.aweb.soa.entity.po.SoaServicePO;
import cn.com.agree.aweb.soa.entity.vo.SoaServiceVO;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;

@Mapper
public interface SoaServiceMapper extends BaseMapper<SoaServicePO, SoaServiceVO> {
    SoaServiceMapper INSTANCE = Mappers.getMapper(SoaServiceMapper.class);
}

第四步:修改controller层报错的地方,主要就是导包。

疑问:如何自己控制那些不生成那些生成?

你可能感兴趣的:(java,mybatis,generator)