您的位置:首页 > 数码常识数码常识

mybatisplus代码生成器使用(mybatis-plus自动生成代码)

2025-05-10人已围观

mybatisplus代码生成器使用(mybatis-plus自动生成代码)
  MyBatis-Plus自定义代码生成模板工具解析最近公司要求开发自定义ORM映射框架,支持DM8达梦数据库、MySQL、Oracle等数据库,本文就Spring Boot自定义MyBatis-Plus生成MySQL数据库进行列举说明,方便大家参考。可实现自定义Controller、实体类等工具。

  mybatis-plus自动生成代码MyBatis-Plus自定义代码生成模板工具解析

  一、添加依赖

  手动添加相关坐标依赖:

  <!-- mybatis代码生成器 -->

  <dependency>

  <groupId>com.baomidou</groupId>

  <artifactId>mybatis-plus-generator</artifactId>

  <version>3.4.0</version>

  </dependency>

  <!-- mybatis核心代码 -->

  <dependency>

  <groupId>com.baomidou</groupId>

  <artifactId>mybatis-plus-core</artifactId>

  <version>3.4.0</version>

  </dependency>

  <!-- 数据库连接 -->

  <dependency>

  <groupId>mysql</groupId>

  <artifactId>mysql-connector-java</artifactId>

  <version>5.1.38</version>

  </dependency>

  <!-- 自定义模版引擎 -->

  <dependency>

  <groupId>org.freemarker</groupId>

  <artifactId>freemarker</artifactId>

  <version>2.3.30</version>

  </dependency>

  <!-- java模版引擎 -->

  <dependency>

  <groupId>org.apache.velocity</groupId>

  <artifactId>velocity</artifactId>

  <version>1.7</version>

  </dependency>

  二、添加bootstrap.yml文件增加MP配置

  mybatis-plus:

  mapper-locations: classpath:/mapper

  @Bean

  @Profile()// 设置 dev test uat环境开启

  public PerformanceInterceptor performanceInterceptor() {

  PerformanceInterceptor performanceInterceptor=new PerformanceInterceptor();

  //performanceInterceptor.setMaxTime(1000);

  //performanceInterceptor.setFormat(true);

  return performanceInterceptor;

  }

  @Bean

  public PaginationInterceptor paginationInterceptor() {

  PaginationInterceptor paginationHxdiInterceptor=new PaginationInterceptor();

  paginationHxdiInterceptor.setLocalPage(true);// 开启 PageHelper 的支持

  return paginationHxdiInterceptor;

  }

  }

  四、代码生成器模板

  @Slf4j

  public class OcdiGenerator {

  // 运行主工具

  public static void main(String[] args) {

  AutoGenerator mpg=new AutoGenerator();

  // 选择 freemarker 引擎,默认 Veloctiy

  // mpg.setTemplateEngine(new FreemarkerTemplateEngine());

  // 全局配置

  GlobalConfig gc=new GlobalConfig();

  gc.setOutputDir("F://ocdi//");

  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("Java功夫");

  // 自定义文件命名,注意 %s 会自动填充表实体属性!

  // gc.setMapperName("%sDao");

  // gc.setXmlName("%sDao");

  // gc.setServiceName("MP%sService");

  // gc.setServiceImplName("%sServiceDiy");

  // gc.setControllerName("%sAction");

  mpg.setGlobalConfig(gc);

  // 数据源配置

  DataSourceConfig dsc=new DataSourceConfig();

  dsc.setDbType(DbType.MYSQL);

  dsc.setTypeConvert(new MySqlTypeConvert(){

  // 自定义数据库表字段类型转换【可选】

  @Override

  public DbColumnType processTypeConvert(String fieldType) {

  System.out.println("转换类型:" + fieldType);

  // 注意!!processTypeConvert 存在默认类型转换,如果不是你要的效果请自定义返回、非如下直接返回。

  return super.processTypeConvert(fieldType);

  }

  });

  dsc.setDriverName("com.mysql.jdbc.Driver");

  dsc.setUsername("root");

  dsc.setPassword("ocdi");

  dsc.setUrl("jdbc:mysql://192.168.3.5:3306/ocr-sba?characterEncoding=utf8");

  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[] { "app_certificate" }); // 需要生成的表

  // strategy.setExclude(new String[]); // 排除生成的表

  // 自定义实体父类

  // strategy.setSuperEntityClass("com.ocdi.demo.TestEntity");

  // 自定义实体,公共字段

  // strategy.setSuperEntityColumns(new String[] { "create_date", "update_date" });

  // 自定义 mapper 父类

  // strategy.setSuperMapperClass("com.ocdi.demo.TestMapper");

  // 自定义 service 父类

  // strategy.setSuperServiceClass("com.ocdi.demo.TestService");

  // 自定义 service 实现类父类

  // strategy.setSuperServiceImplClass("com.ocdi.demo.TestServiceImpl");

  // 自定义 controller 父类

  // strategy.setSuperControllerClass("com.ocdi.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);

  mpg.setStrategy(strategy);

  // 包配置

  PackageConfig pc=new PackageConfig();

  pc.setParent("com.opendi");

  pc.setController("controller");

  pc.setEntity("model");

  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("dce", this.getConfig().getGlobalConfig().getAuthor() + "-mp");

  this.setMap(map);

  }

  };

  // 自定义 xxListIndex 生成

  List<FileOutConfig> focList=new ArrayList<FileOutConfig>();

  focList.add(new FileOutConfig("/templatesMybatis/list.vm") {

  @Override

  public String outputFile(TableInfo tableInfo) {

  // 自定义输入文件名称

  return "F://ocdi//html//" + tableInfo.getEntityName() + "ListIndex";

  }

  });

  cfg.setFileOutConfigList(focList);

  mpg.setCfg(cfg);

  // 自定义 xxAdd 生成

  focList.add(new FileOutConfig("/templatesMybatis/add.vm") {

  @Override

  public String outputFile(TableInfo tableInfo) {

  // 自定义输入文件名称

  return "F://ocdi//html//" + tableInfo.getEntityName() + "Add";

  }

  });

  cfg.setFileOutConfigList(focList);

  mpg.setCfg(cfg);

  // 自定义 xxUpdate生成

  focList.add(new FileOutConfig("/templatesMybatis/update.vm") {

  @Override

  public String outputFile(TableInfo tableInfo) {

  // 自定义输入文件名称

  return "F://ocdi//html//" + tableInfo.getEntityName() + "Update";

  }

  });

  cfg.setFileOutConfigList(focList);

  mpg.setCfg(cfg);

  // 关闭默认 xml 生成,调整生成 至 根目录

  // 自定义模板配置,可以 copy 源码 mybatis-plus/src/main/resources/templates 下面内容修改,

  // 放置自己项目的 src/main/resources/templates 目录下, 默认名称一下可以不配置,也可以自定义模板名称

  TemplateConfig tc=new TemplateConfig();

  tc.setController("/templatesMybatis/controller.java.vm");

  tc.setService("/templatesMybatis/service.java.vm");

  tc.setServiceImpl("/templatesMybatis/serviceImpl.java.vm");

  tc.setEntity("/templatesMybatis/entity.java.vm");

  tc.setMapper("/templatesMybatis/mapper.java.vm");

  tc.setXml("/templatesMybatis/mapper.xml.vm");

  // 如上任何一个模块如果设置 空 OR Null 将不生成该模块。

  mpg.setTemplate(tc);

  // 执行生成

  mpg.execute();

  // 打印注入设置【可无】

  log.info(mpg.getCfg().getMap().get("dce"));

  }

  }

  五、使用的模板示例

  自定义controller模板文件 com

  5.1controller.java.vm

  package ${package.Controller};

  #if(${restControllerStyle})

  import org.springframework.web.bind.annotation.RequestMethod;

  import org.springframework.web.bind.annotation.RestController;

  #else

  import org.springframework.stereotype.Controller;

  #end

  #if(${superControllerClassPackage})

  import ${superControllerClassPackage};

  #end

  import com.alibaba.fastjson.JSON;

  import com..constant.Constant;

  import com.opendi.model.BootStrapTable;

  import org.springframework.ui.Model;

  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 javax.servlet.http.HttpServletRequest;

  import javax.servlet.http.HttpServletResponse;

  import ${package.Service}.${table.serviceName};

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

  import org.slf4j.Logger;

  import org.slf4j.LoggerFactory;

  import java.util.List;

  import java.util.ArrayList;

  import java.util.HashMap;

  import java.util.Map;

  #if(${restControllerStyle})

  @RestController

  #else

  @Controller

  #end

  @RequestMapping("/a#if(${package.ModuleName})/${package.ModuleName}#end/#if(${controllerMappingHyphenStyle})${controllerMappingHyphen}#else${table.entityPath}#end")

  #if(${superControllerClass})

  public class ${table.controllerName} extends ${superControllerClass} {

  #else

  public class ${table.controllerName} {

  #end

  private final Logger logger=LoggerFactory.getLogger(${table.controllerName}.class);

  @Autowired

  public ${table.serviceName} i${entity}Service;

  @RequestMapping(method=RequestMethod.GET,value=)

  public String index(HttpServletRequest request, Model model) {

  return "${table.entityPath}ListIndex";

  }

  @ResponseBody

  @GetMapping("/get${entity}PageList")

  public Map<String, Object> get${entity}List(BootStrapTable<${entity}> bootStrapTable,${entity} ${table.entityPath}) {

  Map<String,Object> result=new HashMap<String,Object>();

  try {

  result=bootStrapTable.setRows(i${entity}Service.selectPage(bootStrapTable,${table.entityPath}));

  } catch (Exception e) {

  logger.error("get${entity}List -=- {}",e.toString());

  result.put(Constant.BOOTSTAP_TABLE_ROWS, new ArrayList<>());

  result.put(Constant.BOOTSTRAP_TABLE_TOTAL, 0);

  }

  return result;

  }

  @RequestMapping(method=RequestMethod.GET,value="/${table.entityPath}Add")

  public String ${table.entityPath}Add(HttpServletRequest request,HttpServletResponse response,Model model) {

  try {

  }catch (Exception ex){

  log.error("${table.entityPath}Add -=- {}",ex.toString());

  }

  return "${table.entityPath}Add";

  }

  @RequestMapping(method=RequestMethod.GET,value="/${table.entityPath}Update")

  public String ${table.entityPath}Update(HttpServletRequest request,Long id) {

  try {

  ${entity} ${table.entityPath}=i${entity}Service.selectById(id);

  request.setAttribute("${table.entityPath}",${table.entityPath});

  }catch (Exception ex){

  log.error("${table.entityPath}Update -=- {}",ex.toString());

  }

  return "${table.entityPath}Upd";

  }

  @ResponseBody

  @RequestMapping(method=RequestMethod.POST,value="/${table.entityPath}Save")

  public int ${table.entityPath}Save(${entity} ${table.entityPath}) {

  int count=0;

  try {

  count=i${entity}Service.insertOrUpdate(${table.entityPath}) ? 1 : 0;

  } catch (Exception e) {

  log.error("${table.entityPath}Save -=- {}",e.toString());

  }

  return count;

  }

  @ResponseBody

  @RequestMapping(method=RequestMethod.POST,value="/${table.entityPath}Delete")

  public int ${table.entityPath}Delete(Long id){

  int count=0;

  try {

  count=i${entity}Service.deleteById(id) ? 1 : 0;

  }catch (Exception e){

  log.error("${table.entityPath}Delete -=- {}",e.toString());

  }

  return count;

  }

  @ResponseBody

  @RequestMapping(method=RequestMethod.POST,value="/${table.entityPath}BatchDelete")

  public int deleteBatchIds(String item){

  int count=0;

  try {

  List<Long> ids=(List<Long>) JSON.parse(item);

  count=i${entity}Service.deleteBatchIds(ids) ? 1 : 0;

  }catch (Exception e){

  log.error("${table.entityPath}BatchDelete -=- {}",e.toString());

  }

  return count;

  }

  }

  5.2entity.java.vm

  package ${package.Entity};

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

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

  import com.baomidou.mybatisplus.annotations.Version;

  import lombok.Data;import lombok.experimental.Accessors;#end

  #if(${entityLombokModel})@Data@Accessors(chain=true)#end#if(${table.convert})@TableName("${table.name}")#end#if(${superEntityClass})public class ${entity} extends ${superEntityClass}#if(${activeRecord})<${entity}>#end {#elseif(${activeRecord})public class ${entity} extends Model<${entity}> {#elsepublic class ${entity} implements Serializable {#end

  private static final long serialVersionUID=1L;

  ## ---------- BEGIN 字段循环遍历 ----------#foreach($field in ${table.fields})#if(${field.keyFlag})#set($keyPropertyName=${field.propertyName})#end#if("$!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#endprivate ${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}) {#elsepublic void set${field.capitalName}(${field.propertyType} ${field.propertyName}) {#endthis.${field.propertyName}=${field.propertyName};#if(${entityBuilderModel})return this;#end}#end#end

  #if(${entityColumnConstant})#foreach($field in ${table.fields})public static final String ${field.name.toUpperCase()}="${field.name}";

  #end#end#if(${activeRecord})@Overrideprotected Serializable pkVal() {#if(${keyPropertyName})return this.${keyPropertyName};#elsereturn this.id;#end}

  #end#if(!${entityLombokModel})@Overridepublic String toString() {return "${entity}

  5.3mapper.java.vm

  package ${package.Mapper};

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

  public interface ${table.mapperName} extends ${superMapperClass}<${entity}> {

  }

  mapper.xml.vm

  <?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}">

  #if(${enableCache})<!-- 开启二级缓存 --><cache type="org.mybatis.caches.ehcache.LoggingEhcache"/>

  #end#if(${baseResultMap})<!-- 通用查询映射结果 --><resultMap type="${package.Entity}.${entity}">#foreach($field in ${table.fields})#if(${field.keyFlag})##生成主键排在第一位<id column="${field.name}" property="${field.propertyName}" />#end#end#foreach($field in ${table.commonFields})##生成公共字段<result column="${field.name}" property="${field.propertyName}" />#end#foreach($field in ${table.fields})#if(!${field.keyFlag})##生成普通字段<result column="${field.name}" property="${field.propertyName}" />#end#end</resultMap>

  #end#if(${baseColumnList})<!-- 通用查询结果列 --><sql>#foreach($field in ${table.commonFields})#if(${field.name}==${field.propertyName})${field.name}#else${field.name} AS ${field.propertyName}#end,#end${table.fieldNames}</sql>#end</mapper>

  5.4 service.java.vm

  package ${package.Service};

  import com.baomidou.mybatisplus.plugins.Page;import ${package.Entity}.${entity};import ${superServiceClassPackage};import com.opendi.model.BootStrapTable;

  import java.util.List;

  public interface ${table.serviceName} extends ${superServiceClass}<${entity}> {

  Page<${entity}> selectPage(BootStrapTable<${entity}> bootStrapTable,${entity} ${table.entityPath});

  List<HxdiType> selectList(${entity} ${table.entityPath});}

  5.5 serviceImpl.java.vm

  package ${package.ServiceImpl};

  import com.baomidou.mybatisplus.mapper.EntityWrapper;import com.baomidou.mybatisplus.plugins.Page;import com.opendi.model.BootStrapTable;import ${package.Entity}.${entity};import ${package.Mapper}.${table.mapperName};import ${package.Service}.${table.serviceName};import ${superServiceImplClassPackage};import org.springframework.stereotype.Service;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.transaction.annotation.Transactional;import com.opendi.utils.lang.StringUtils;

  import java.util.List;@Service@Transactionalpublic class ${table.serviceImplName} extends ${superServiceImplClass}<${table.mapperName}, ${entity}> implements ${table.serviceName} {

  @Autowiredprivate ${table.mapperName} ${table.entityPath}Mapper;

  @Overridepublic Page<${entity}> selectPage(BootStrapTable<${entity}> bootStrapTable, ${entity} ${table.entityPath}) {EntityWrapper<${entity}> entityWrapper=new EntityWrapper<${entity}>();getEntityWrapper(entityWrapper,${table.entityPath});return super.selectPage(bootStrapTable.getPagePlus(),entityWrapper);}

  @Overridepublic List<${entity}> selectList(${entity} ${table.entityPath}) {EntityWrapper<${entity}> entityWrapper=new EntityWrapper<${entity}>();getEntityWrapper(entityWrapper,${table.entityPath});return super.selectList(entityWrapper);}

  public EntityWrapper<${entity}> getEntityWrapper(EntityWrapper<${entity}> entityWrapper,${entity} ${table.entityPath}){//条件拼接#foreach($field in ${table.fields})#if(!${field.keyFlag})if (StringUtils.isNotBlank(${table.entityPath}.${getprefix}${field.capitalName}())){entityWrapper.like(${entity}.${field.name.toUpperCase()},${table.entityPath}.${getprefix}${field.capitalName}());}#end#endreturn entityWrapper;}}

  html 页面代码生成器 前端页面使用super ui 可自行修改 基本语法一样的

  5.6 update.vm

  默认都不能为空,生成之后 自行删减

  <!DOCTYPE html><html lang="en" xmlns="http://ment}</label><div><input name="${field.propertyName}" value=""/></div></div>#end#end

  <div><label></label><div><button type="submit"><i></i> 保存</button><button type="button" οnclick="layer_close();"><iclass="fa fa-close"></i> 关闭</button></div></div></div></form></div></section></body><div th:replace="common/common_foot :: foot"></div><script th:src="http://sjzlt.cn/shuma/@{/content/plugins/jquery.validation/jquery.validate.js}"></script><script th:src="http://sjzlt.cn/shuma/@{/content/plugins/jquery.validation/validate-methods.js}"></script><script th:src="http://sjzlt.cn/shuma/@{/content/common/validation/common.validation.js}"></script><script th:inline="javascript">#macro(dian).#end #set($bootstrapTable='$table')

  $(function () {$(".select2").select2({placeholder: "请选择",width: "100%" //设置下拉框的宽度});$('input[type="checkbox"].minimal, input[type="radio"].minimal').iCheck({checkboxClass: 'icheckbox_square-blue',radioClass: 'iradio_square-blue',increaseArea: '20%' // optional});$("#form-admin-add").validate({rules: {#foreach($field in ${table.fields})#if(!${field.keyFlag})##生成普通字段${field.propertyName}: {required: true}#if(${table.fields.size()} !=${velocityCount}),#end#end#end},onkeyup: false,submitHandler: function (form) {$.ajax({url: getRootPath()+"/a/${table.entityPath}/${table.entityPath}Save",type: "Post",dataType: "json",data: $(form).serialize(),success: function (result) {if (result > 0) {opaler();} else {opalerNO();}//刷新父级页面parent.$bootstrapTable#dian()bootstrapTable('refresh'); //再刷新DT}});}});});</script></html>

  上面就是小居数码小编今天给大家介绍的关于(mybatis-plus自动生成代码)的全部内容,希望可以帮助到你,想了解更多关于数码知识的问题,欢迎关注我们,并收藏,转发,分享。

  94%的朋友还想知道的:

  wps中word表格怎么自动生成序号(wps文档表格如何连续编号)

  word自动生成目录设置方法步骤(word自动生成目录怎么设置)

  word自动生成目录怎么操作步骤(word怎样一键生成目录)

  无法激活的解决办法(autocad2020安装失败错误代码1603)



  153028
 

很赞哦! ()

随机图文