1 目录结构

  1. ├─src
  2. ├─main
  3. ├─java
  4. └─com
  5. └─hikktn
  6. ├─common
  7. ├─base
  8. ├─enums
  9. ├─exception
  10. ├─rest
  11. └─validator
  12. ├─content
  13. ├─controller
  14. ├─dao
  15. ├─entity
  16. └─service
  17. └─impl
  18. └─generator
  19. └─resources
  20. ├─mapper
  21. └─templates

2 示例

2.1 依赖引入

  1. <parent>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-parent</artifactId>
  4. <version>2.1.3.RELEASE</version>
  5. </parent>
  6. <dependencies>
  7. <dependency>
  8. <groupId>org.springframework.boot</groupId>
  9. <artifactId>spring-boot-starter</artifactId>
  10. </dependency>
  11. <dependency>
  12. <groupId>org.springframework.boot</groupId>
  13. <artifactId>spring-boot-starter-test</artifactId>
  14. <scope>test</scope>
  15. </dependency>
  16. <dependency>
  17. <groupId>org.springframework.boot</groupId>
  18. <artifactId>spring-boot-starter-web</artifactId>
  19. </dependency>
  20. <!--mybatis-plus的springboot支持-->
  21. <dependency>
  22. <groupId>com.baomidou</groupId>
  23. <artifactId>mybatis-plus-boot-starter</artifactId>
  24. <version>3.1.0</version>
  25. </dependency>
  26. <dependency>
  27. <groupId>com.baomidou</groupId>
  28. <artifactId>mybatis-plus-generator</artifactId>
  29. <version>3.1.0</version>
  30. </dependency>
  31. <!-- MP 核心库 -->
  32. <dependency>
  33. <groupId>com.baomidou</groupId>
  34. <artifactId>mybatis-plus</artifactId>
  35. <version>3.1.0</version>
  36. </dependency>
  37. <!--mysql驱动-->
  38. <dependency>
  39. <groupId>mysql</groupId>
  40. <artifactId>mysql-connector-java</artifactId>
  41. </dependency>
  42. <!--简化代码的工具包-->
  43. <dependency>
  44. <groupId>org.projectlombok</groupId>
  45. <artifactId>lombok</artifactId>
  46. </dependency>
  47. <!-- 模板引擎依赖Freemarker -->
  48. <dependency>
  49. <groupId>org.freemarker</groupId>
  50. <artifactId>freemarker</artifactId>
  51. <version>2.3.29</version>
  52. </dependency>
  53. <!-- thymeleaf模板插件 -->
  54. <dependency>
  55. <groupId>org.springframework.boot</groupId>
  56. <artifactId>spring-boot-starter-thymeleaf</artifactId>
  57. </dependency>
  58. <dependency>
  59. <groupId>commons-fileupload</groupId>
  60. <artifactId>commons-fileupload</artifactId>
  61. <version>1.3</version>
  62. </dependency>
  63. <!-- velocity -->
  64. <dependency>
  65. <groupId>org.apache.velocity</groupId>
  66. <artifactId>velocity</artifactId>
  67. <version>1.7</version>
  68. </dependency>
  69. <dependency>
  70. <groupId>io.springfox</groupId>
  71. <artifactId>springfox-swagger2</artifactId>
  72. <version>2.9.2</version>
  73. </dependency>
  74. <dependency>
  75. <groupId>io.springfox</groupId>
  76. <artifactId>springfox-swagger-ui</artifactId>
  77. <version>2.9.2</version>
  78. </dependency>
  79. <dependency>
  80. <groupId>com.alibaba</groupId>
  81. <artifactId>fastjson</artifactId>
  82. <version>1.2.75</version>
  83. </dependency>
  84. </dependencies>

2.2 控制器 - controller.java.vm

  1. package ${package.Controller};
  2. import ${package.Entity}.${entity};
  3. import ${package.Service}.${table.serviceName};
  4. import com.hikktn.common.base.PageDto;
  5. import com.hikktn.common.exception.RestException;
  6. import com.hikktn.common.rest.RestResponse;
  7. import org.apache.commons.lang.StringUtils;
  8. import org.springframework.web.bind.annotation.*;
  9. import io.swagger.annotations.Api;
  10. import io.swagger.annotations.ApiOperation;
  11. import org.springframework.beans.factory.annotation.Autowired;
  12. import org.springframework.http.MediaType;
  13. #if(${superControllerClassPackage})
  14. import $!{superControllerClassPackage};
  15. #end
  16. /**
  17. * <p>
  18. * $!{table.comment} 前端控制器
  19. * </p>
  20. *
  21. * @author ${author}
  22. * @since ${date}
  23. * @version ${cfg.version}
  24. */
  25. #set($entityName = ${entity.substring(0,1).toLowerCase()}+${entity.substring(1)})
  26. @RestController
  27. @RequestMapping(value = {"#if(${controllerMappingHyphenStyle})/api/${controllerMappingHyphen}#else /api/${table.entityPath}#end"},
  28. produces = MediaType.APPLICATION_JSON_VALUE)
  29. @Api(value = "${table.controllerName}", description = "$!{table.comment}", produces = MediaType.APPLICATION_JSON_VALUE)
  30. public class ${table.controllerName} extends ${superControllerClass} {
  31. @Autowired
  32. private ${table.serviceName} ${entityName}Service;
  33. @ResponseBody
  34. @ApiOperation(value = "$!{table.comment}-分页查询", notes = "$!{table.comment}-分页查询")
  35. @RequestMapping(value = "/_search", method = RequestMethod.POST)
  36. public RestResponse search(@RequestBody PageDto<${entity}> page){
  37. return RestResponse.success();
  38. }
  39. @ResponseBody
  40. @ApiOperation(value = "$!{table.comment}-保存", notes = "$!{table.comment}-保存")
  41. @RequestMapping(value = "", method = RequestMethod.POST)
  42. public RestResponse<String> save(@RequestBody ${entity} $entityName){
  43. ${entityName}Service.save($entityName);
  44. return RestResponse.success();
  45. }
  46. @ResponseBody
  47. @ApiOperation(value = "$!{table.comment}-更新", notes = "$!{table.comment}-更新")
  48. @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
  49. public RestResponse<String> update(@PathVariable String id, @RequestBody ${entity} $entityName){
  50. if (StringUtils.isEmpty(id)){
  51. throw new RestException("ID不能为空");
  52. }
  53. ${entityName}Service.updateById($entityName);
  54. return RestResponse.success();
  55. }
  56. @ResponseBody
  57. @ApiOperation(value = "$!{table.comment}-删除", notes = "$!{table.comment}-删除")
  58. @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
  59. public RestResponse<String> delete(@PathVariable String id){
  60. ${entityName}Service.removeById(id);
  61. return RestResponse.success();
  62. }
  63. }

2.3 领域对象 - entity.java.vm

  1. package ${package.Entity};
  2. #foreach($pkg in ${table.importPackages})
  3. import ${pkg};
  4. #end
  5. #if(${entityLombokModel})
  6. import lombok.Data;
  7. import lombok.EqualsAndHashCode;
  8. import lombok.experimental.Accessors;
  9. #end
  10. #if(${swagger2})
  11. import io.swagger.annotations.ApiModelProperty;
  12. #end
  13. ## 表备注,作者,日期
  14. /**
  15. * <p>
  16. * $!{table.comment}
  17. * </p>
  18. *
  19. * @author ${author}
  20. * @since ${date}
  21. * @version ${cfg.version}
  22. */
  23. #if(${entityLombokModel})
  24. @Data
  25. @EqualsAndHashCode(callSuper = true)
  26. @Accessors(chain = true)
  27. #end
  28. @TableName("${table.name}")
  29. #if(${superEntityClass})
  30. public class ${entity} extends ${superEntityClass}#if(${activeRecord})<${entity}>#end {
  31. #elseif(${activeRecord})
  32. public class ${entity} extends Model<${entity}> {
  33. #else
  34. public class ${entity} implements Serializable {
  35. #end
  36. private static final long serialVersionUID = 1L;
  37. ## ---------- BEGIN 字段循环遍历 ----------
  38. ## ---------- START 字段循环遍历 ----------
  39. #foreach($field in ${table.fields})
  40. #if(${field.keyFlag})
  41. #set($keyPropertyName=${field.propertyName})
  42. #end
  43. #if("$!field.comment" != "")
  44. #if(${swagger2})
  45. /**
  46. * ${field.comment}
  47. */
  48. @ApiModelProperty(value = "${field.comment}")
  49. #else
  50. /**
  51. * ${field.comment}
  52. */
  53. #end
  54. #end
  55. ## 主键
  56. #if(${field.keyFlag})
  57. #if(${field.keyIdentityFlag})
  58. @TableId(value = "${field.name}", type = IdType.AUTO)
  59. #elseif(!$null.isNull(${idType}) && "$!idType" != "")
  60. @TableId(value = "${field.name}", type = IdType.${idType})
  61. #elseif(${field.convert})
  62. @TableId("${field.name}")
  63. #end
  64. ## 普通字段
  65. #if(${field.fill})
  66. ## ----- 存在字段填充设置 -----
  67. #if(${field.convert})
  68. @TableField(value = "${field.name}", fill = FieldFill.${field.fill})
  69. #else
  70. @TableField(fill = FieldFill.${field.fill})
  71. #end
  72. #elseif(${field.convert})
  73. @TableField("${field.name}")
  74. #end
  75. #end
  76. ## 时间类型
  77. #if(${field.name} == ${cfg.createTime})
  78. @TableField(fill = FieldFill.INSERT)
  79. #elseif(${field.name} == ${cfg.updateTime})
  80. @TableField(fill = FieldFill.INSERT_UPDATE)
  81. #end
  82. ## 逻辑删除注解
  83. #if(${cfg.logicDeleteFieldName}==${field.name})
  84. @TableLogic
  85. #end
  86. private ${field.propertyType} ${field.propertyName};
  87. #end
  88. ## ---------- END 字段循环遍历 ----------
  89. #if(!${entityLombokModel})
  90. #foreach($field in ${table.fields})
  91. #if(${field.propertyType.equals("boolean")})
  92. #set($getprefix="is")
  93. #else
  94. #set($getprefix="get")
  95. #end
  96. public ${field.propertyType} ${getprefix}${field.capitalName}() {
  97. return ${field.propertyName};
  98. }
  99. #if(${entityBuilderModel})
  100. public ${entity} set${field.capitalName}(${field.propertyType} ${field.propertyName}) {
  101. #else
  102. public void set${field.capitalName}(${field.propertyType} ${field.propertyName}) {
  103. #end
  104. this.${field.propertyName} = ${field.propertyName};
  105. #if(${entityBuilderModel})
  106. return this;
  107. #end
  108. }
  109. #end
  110. ## --foreach end---
  111. #end
  112. ## --end of
  113. #if(${entityColumnConstant})
  114. #foreach($field in ${table.fields})
  115. public static final String ${field.name.toUpperCase()} = "${field.name}";
  116. #end
  117. #end
  118. #if(${activeRecord})
  119. @Override
  120. protected Serializable pkVal() {
  121. #if(${keyPropertyName})
  122. return this.${keyPropertyName};
  123. #else
  124. return this.id;
  125. #end
  126. }
  127. #end
  128. #if(!${entityLombokModel})
  129. @Override
  130. public String toString() {
  131. return "${entity}{" +
  132. #foreach($field in ${table.fields})
  133. #if($!{velocityCount}==1)
  134. "${field.propertyName}=" + ${field.propertyName} +
  135. #else
  136. ", ${field.propertyName}=" + ${field.propertyName} +
  137. #end
  138. #end
  139. "}";
  140. }
  141. #end
  142. }

2.4 Mapper接口 - mapper.java.vm

  1. package ${package.Mapper};
  2. import ${package.Entity}.${entity};
  3. import ${superMapperClassPackage};
  4. import org.springframework.stereotype.Repository;
  5. /**
  6. * <p>
  7. * $!{table.comment} Mapper 接口
  8. * </p>
  9. *
  10. * @author ${author}
  11. * @since ${date}
  12. * @version ${cfg.version}
  13. */
  14. @Repository
  15. public interface ${table.mapperName} extends ${superMapperClass}<${entity}> {
  16. }

2.5 Mapper-XML - mapper.xml.vm

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="${package.Mapper}.${table.mapperName}">
  4. #if(${enableCache})
  5. <!-- 开启二级缓存 -->
  6. <cache type="org.mybatis.caches.ehcache.LoggingEhcache"/>
  7. #end
  8. #if(${baseResultMap})
  9. <!-- 通用查询映射结果 -->
  10. <resultMap id="BaseResultMap" type="${package.Entity}.${entity}">
  11. #foreach($field in ${table.fields})
  12. #if(${field.keyFlag})##生成主键排在第一位
  13. <id column="${field.name}" property="${field.propertyName}"/>
  14. #end
  15. #end
  16. #foreach($field in ${table.commonFields})##生成公共字段
  17. <result column="${field.name}" property="${field.propertyName}"/>
  18. #end
  19. #foreach($field in ${table.fields})
  20. #if(!${field.keyFlag})##生成普通字段
  21. <result column="${field.name}" property="${field.propertyName}"/>
  22. #end
  23. #end
  24. </resultMap>
  25. #end
  26. #if(${baseColumnList})
  27. <!-- 通用查询结果列 -->
  28. <sql id="Base_Column_List">
  29. #foreach($field in ${table.commonFields})
  30. #if(${field.name} == ${field.propertyName})${field.name}#else${field.name} AS ${field.propertyName}#end,
  31. #end
  32. ${table.fieldNames}
  33. </sql>
  34. #end
  35. </mapper>

2.6 业务层 - service.java.vm

  1. package ${package.Service};
  2. import com.hikktn.common.base.PageDto;
  3. import ${package.Entity}.${entity};
  4. import ${superServiceClassPackage};
  5. /**
  6. * <p>
  7. * $!{table.comment} 服务类
  8. * </p>
  9. *
  10. * @author ${author}
  11. * @since ${date}
  12. * @version ${cfg.version}
  13. */
  14. #set($entityName = ${entity.substring(0,1).toLowerCase()}+${entity.substring(1)})
  15. public interface ${table.serviceName} extends ${superServiceClass}<${entity}> {
  16. /**
  17. * 添加
  18. * @param $entityName
  19. */
  20. @Override
  21. boolean save(${entity} $entityName);
  22. /**
  23. * 分页查询
  24. * @param pageDto 分页
  25. * @return
  26. */
  27. PageDto<${entity}> page(PageDto<${entity}> pageDto);
  28. }

2.7 业务实现层 - serviceImpl.java.vm

  1. package ${package.ServiceImpl};
  2. import ${package.Entity}.${entity};
  3. import ${package.Mapper}.${table.mapperName};
  4. import ${package.Service}.${table.serviceName};
  5. import ${superServiceImplClassPackage};
  6. import com.hikktn.common.base.PageDto;
  7. import org.springframework.stereotype.Service;
  8. import com.hikktn.common.validator.ValidatorUtils;
  9. import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
  10. /**
  11. * <p>
  12. * $!{table.comment} 服务实现类
  13. * </p>
  14. *
  15. * @author ${author}
  16. * @since ${date}
  17. * @version ${cfg.version}
  18. */
  19. #set($entityName = ${entity.substring(0,1).toLowerCase()}+${entity.substring(1)})
  20. @Service
  21. public class ${table.serviceImplName} extends ${superServiceImplClass}<${table.mapperName}, ${entity}> implements ${table.serviceName} {
  22. @Override
  23. public boolean save(${entity} $entityName) {
  24. ValidatorUtils.validateEntity($entityName);
  25. return this.save($entityName);
  26. }
  27. @Override
  28. public PageDto<${entity}> page(PageDto<${entity}> pageDto) {
  29. QueryWrapper<${entity}> ew = new QueryWrapper<>();
  30. return new PageDto<>(super.page(pageDto.getDbPage(), ew));
  31. }
  32. }

2.8 appliaction.yml

  1. spring:
  2. application:
  3. name: mybatis-plus-demo
  4. datasource:
  5. driver-class-name: com.mysql.cj.jdbc.Driver
  6. url: jdbc:mysql://127.0.0.1:3306/my_mybatis_plus?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true
  7. username: root
  8. password: 123456
  9. #logging:
  10. # level:
  11. # root: debug
  12. mybatis-plus:
  13. # 读取mybatis配置文件
  14. # config-location: classpath:mybatis/mybatis-config.xml
  15. # 读取mapper文件
  16. # mapper-locations: classpath*:mybatis/mapper/*Mapper.xml
  17. # 别名配置,在mybatis.xml文件resultType属性可以不指定类的全路径
  18. # type-aliases-package: com.hikktn.pojo
  19. # 开启驼峰映射,注意:配置configuration.map-underscore-to-camel-case则不能配置config-location
  20. # configuration:
  21. # map-underscore-to-camel-case: true
  22. # 日志
  23. configuration:
  24. log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  25. # 逻辑删除
  26. global-config:
  27. db-config:
  28. logic-delete-value: 1 # 逻辑已删除值(默认为 1)
  29. logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)

2.9 生成类

  1. package com.hikktn.generator;
  2. import com.baomidou.mybatisplus.annotation.DbType;
  3. import com.baomidou.mybatisplus.annotation.IdType;
  4. import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
  5. import com.baomidou.mybatisplus.core.toolkit.StringPool;
  6. import com.baomidou.mybatisplus.core.toolkit.StringUtils;
  7. import com.baomidou.mybatisplus.generator.AutoGenerator;
  8. import com.baomidou.mybatisplus.generator.InjectionConfig;
  9. import com.baomidou.mybatisplus.generator.config.*;
  10. import com.baomidou.mybatisplus.generator.config.po.TableInfo;
  11. import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
  12. import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
  13. import com.baomidou.mybatisplus.generator.engine.VelocityTemplateEngine;
  14. import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
  15. import org.springframework.core.io.ClassPathResource;
  16. import java.util.*;
  17. /**
  18. * @ClassName MpGenerator
  19. * @Description Mybatis-Plus代码生成器
  20. * @Author lisonglin
  21. * @Date 2021/5/30 15:09
  22. * @Version 1.0
  23. */
  24. public class MyGenerator {
  25. // TODO 修改服务名以及数据表名
  26. /**
  27. * 顶层包名
  28. */
  29. private static final String SERVICE_NAME = "content";
  30. /**
  31. * 最终包路径
  32. */
  33. private static final StringBuilder FINAL_PATH = new StringBuilder();
  34. /**
  35. * 多个数据表名
  36. */
  37. private static final String[] TABLE_NAMES = new String[]{"tb_user", "t_area"};
  38. /**
  39. * <p>
  40. * 读取控制台内容
  41. * </p>
  42. */
  43. public static String scanner(String tip) {
  44. Scanner scanner = new Scanner(System.in);
  45. StringBuilder help = new StringBuilder();
  46. help.append("请输入" + tip + ":");
  47. System.out.println(help);
  48. if (scanner.hasNext()) {
  49. String ipt = scanner.next();
  50. if (StringUtils.isNotEmpty(ipt)) {
  51. return ipt;
  52. }
  53. }
  54. throw new MybatisPlusException("请输入正确的" + tip + "!");
  55. }
  56. /**
  57. * 代码生成器
  58. */
  59. public static void main(String[] args) {
  60. // 目标数据表名
  61. String[] tableName = scanner("表名,多个英文逗号分割").split(",");
  62. generateByTables(tableName);
  63. }
  64. private static void generateByTables(String... tableNames) {
  65. // 选择 freemarker 引擎,默认 Velocity
  66. AutoGenerator mpg = new AutoGenerator();
  67. // mpg.setTemplateEngine(new FreemarkerTemplateEngine());
  68. mpg.setTemplateEngine(new VelocityTemplateEngine());
  69. // 全局配置
  70. GlobalConfig gc = globalGenerate();
  71. // 包配置
  72. PackageConfig pc = packageGenerate();
  73. // 文件路径输出配置
  74. List<FileOutConfig> foc = fileOutGenerate(pc);
  75. // 其他参数
  76. InjectionConfig cfg = injectionGenerate(foc);
  77. // 数据库配置
  78. DataSourceConfig dsc = dataSourceGenerate();
  79. // 自定义模板
  80. TemplateConfig tc = templateGenerate();
  81. // 策略配置
  82. StrategyConfig strategy = strategyGenerate(tableNames);
  83. mpg.setGlobalConfig(gc);
  84. mpg.setDataSource(dsc);
  85. mpg.setPackageInfo(pc);
  86. mpg.setCfg(cfg);
  87. mpg.setTemplate(tc);
  88. mpg.setStrategy(strategy);
  89. mpg.execute();
  90. }
  91. /**
  92. * 数据库配置
  93. *
  94. * @return 数据源
  95. */
  96. private static DataSourceConfig dataSourceGenerate() {
  97. YamlPropertiesFactoryBean yamlMapFactoryBean = new YamlPropertiesFactoryBean();
  98. yamlMapFactoryBean.setResources(new ClassPathResource("application.yml"));
  99. //获取yml里的参数
  100. Properties properties = yamlMapFactoryBean.getObject();
  101. String url = properties.getProperty("spring.datasource.url");
  102. String driver = properties.getProperty("spring.datasource.driver-class-name");
  103. String username = properties.getProperty("spring.datasource.username");
  104. String password = properties.getProperty("spring.datasource.password");
  105. // 数据库配置
  106. DataSourceConfig dsc = new DataSourceConfig();
  107. //数据类型
  108. dsc.setDbType(DbType.MYSQL);
  109. dsc.setUrl(url);
  110. dsc.setDriverName(driver);
  111. dsc.setUsername(username);
  112. dsc.setPassword(password);
  113. return dsc;
  114. }
  115. /**
  116. * 全局配置
  117. *
  118. * @return 全局配置
  119. */
  120. private static GlobalConfig globalGenerate() {
  121. // 全局配置
  122. GlobalConfig gc = new GlobalConfig();
  123. //是否覆盖文件
  124. gc.setFileOverride(true);
  125. // 获取顶层目录
  126. String projectPath = System.getProperty("user.dir");
  127. // 获取子项目目录
  128. String path = MyGenerator.class.getClassLoader().getResource("").getPath();
  129. String levelPath = path.substring(0, path.indexOf("target") - 1);
  130. if (!projectPath.equals(levelPath)) {
  131. FINAL_PATH.append(levelPath);
  132. } else {
  133. FINAL_PATH.append(projectPath);
  134. }
  135. //输出路径
  136. gc.setOutputDir(FINAL_PATH + "/src/main/java");
  137. //作者名称
  138. gc.setAuthor("hikktn");
  139. //生成后是否自动打开文件
  140. gc.setOpen(false);
  141. // XML 二级缓存
  142. gc.setEnableCache(false);
  143. //是否使用swagger2
  144. gc.setSwagger2(true);
  145. // 自定义文件命名,注意 %s 会自动填充表实体属性!
  146. gc.setControllerName("%sController");
  147. gc.setServiceName("%sService");
  148. gc.setServiceImplName("%sServiceImpl");
  149. gc.setMapperName("%sMapper");
  150. gc.setXmlName("%sMapper");
  151. //mapper.xml中生成基础resultMap
  152. gc.setBaseResultMap(true);
  153. //mapper.xml中生成基础columnList
  154. gc.setBaseColumnList(true);
  155. // 主键类型
  156. gc.setIdType(IdType.ID_WORKER);
  157. return gc;
  158. }
  159. /**
  160. * 策略配置
  161. * 主要的表字段映射
  162. *
  163. * @param tableName 表名
  164. * @return 策略配置
  165. */
  166. private static StrategyConfig strategyGenerate(String[] tableName) {
  167. // 策略配置
  168. StrategyConfig strategy = new StrategyConfig();
  169. //表名映射到实体策略,带下划线的转成 驼峰
  170. strategy.setNaming(NamingStrategy.underline_to_camel);
  171. //列名映射到类型属性策略,带下划线的转成驼峰
  172. strategy.setColumnNaming(NamingStrategy.underline_to_camel);
  173. // 表名和字段名是否大小写
  174. strategy.setCapitalMode(false);
  175. //实体类使用lombok
  176. strategy.setEntityLombokModel(false);
  177. //controller使用rest接口模式
  178. strategy.setRestControllerStyle(true);
  179. // 继承顶层controller
  180. strategy.setSuperControllerClass("com.hikktn.common.base.BaseController");
  181. //设置表名
  182. strategy.setInclude(tableName);
  183. //strategy.setInclude(TABLE_NAMES);
  184. //表名映射到实体名称去掉前缀
  185. strategy.setTablePrefix("tb_");
  186. // Boolean类型字段是否移除is前缀处理
  187. strategy.setEntityBooleanColumnRemoveIsPrefix(true);
  188. // 驼峰转连字符
  189. strategy.setControllerMappingHyphenStyle(true);
  190. // 建造者模式
  191. strategy.setEntityBuilderModel(true);
  192. return strategy;
  193. }
  194. /**
  195. * 自定义模板
  196. *
  197. * @return 模板
  198. */
  199. private static TemplateConfig templateGenerate() {
  200. // 设置模板
  201. TemplateConfig tc = new TemplateConfig();
  202. tc.setController("templates/controller.java.vm")
  203. .setEntity("templates/entity.java.vm")
  204. .setService("templates/service.java.vm")
  205. .setServiceImpl("templates/serviceImpl.java.vm")
  206. .setMapper("templates/mapper.java.vm")
  207. // 不要源码包内的mapper
  208. .setXml(null);
  209. return tc;
  210. }
  211. /**
  212. * 文件路径输出配置
  213. *
  214. * @param pc 包配置
  215. * @return 文件路径输出配置
  216. */
  217. private static List<FileOutConfig> fileOutGenerate(PackageConfig pc) {
  218. String templatePath = "/templates/mapper.xml.vm";
  219. // 自定义输出配置
  220. List<FileOutConfig> focList = new ArrayList<>();
  221. // 自定义配置会被优先输出
  222. focList.add(new FileOutConfig(templatePath) {
  223. @Override
  224. public String outputFile(TableInfo tableInfo) {
  225. // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
  226. return FINAL_PATH + "/src/main/resources/mapper/"
  227. + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
  228. }
  229. });
  230. return focList;
  231. }
  232. /**
  233. * 其他参数,在velocity使用的参数,格式:${cfg.version}
  234. *
  235. * @param focList 文件路径输出配置
  236. * @return 其他参数
  237. */
  238. private static InjectionConfig injectionGenerate(List<FileOutConfig> focList) {
  239. InjectionConfig cfg = new InjectionConfig() {
  240. @Override
  241. public void initMap() {
  242. Map<String, Object> map = new HashMap<>(10);
  243. // 查询参数名
  244. map.put("version", "1.0");
  245. // 逻辑删除
  246. map.put("logicDeleteFieldName","is_deleted");
  247. // 创建时间(自动生成时间)
  248. map.put("createTime","create_time");
  249. // 修改时间
  250. map.put("updateTime","update_time");
  251. this.setMap(map);
  252. }
  253. };
  254. cfg.setFileOutConfigList(focList);
  255. return cfg;
  256. }
  257. /**
  258. * 包配置
  259. *
  260. * @return 包配置
  261. */
  262. private static PackageConfig packageGenerate() {
  263. // 包配置
  264. PackageConfig pc = new PackageConfig();
  265. pc.setModuleName(SERVICE_NAME);
  266. pc.setParent("com.hikktn");
  267. pc.setEntity("entity");
  268. pc.setService("service");
  269. pc.setServiceImpl("service.impl");
  270. pc.setMapper("dao");
  271. // 不要设置包目录,否则会生成到源码包内
  272. pc.setXml(null);
  273. return pc;
  274. }
  275. }