当前位置:   article > 正文

mybatis-plus-generator(mybatisplus代码生成器篇)

mybatis-plus-generator

前言:mybatisplus用了也挺久了,期间用过mybatis的代码生成器,那个主要生成mapper.xml文件,里面基本涵盖了绝大多数常用的方法;项目也用过一些开源框架自带的代码生成器,比如jeecg-boot框架自带的代码生成器,不过那个由于做了一些自定义封装,普适性不是很好,今天记录一下mybatis-plus代码生成器的简单使用(生成基本的controller、service、mapper、mapper.xml),如果感觉功能太少,可以在mybatis-plus自带的模板引擎demo基础上进行自定义改造,下面我们开始正篇吧,废话不多说,上代码:

maven依赖自己酌情增减:

  1. <parent>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-parent</artifactId>
  4. <version>2.3.5.RELEASE</version>
  5. <relativePath/>
  6. </parent>
  7. <properties>
  8. <java.version>1.8</java.version>
  9. <lombok.version>1.18.16</lombok.version>
  10. <freemarker.version>2.3.30</freemarker.version>
  11. <mybatis-plus.version>3.4.1</mybatis-plus.version>
  12. <druid.version>1.1.22</druid.version>
  13. <mysql.version>8.0.22</mysql.version>
  14. </properties>
  15. <dependencies>
  16. <dependency>
  17. <groupId>org.springframework.boot</groupId>
  18. <artifactId>spring-boot-starter-web</artifactId>
  19. </dependency>
  20. <!--mysql数据库依赖-->
  21. <dependency>
  22. <groupId>org.springframework.boot</groupId>
  23. <artifactId>spring-boot-starter-jdbc</artifactId>
  24. </dependency>
  25. <dependency>
  26. <groupId>mysql</groupId>
  27. <artifactId>mysql-connector-java</artifactId>
  28. <version>${mysql.version}</version>
  29. </dependency>
  30. <dependency>
  31. <groupId>com.alibaba</groupId>
  32. <artifactId>druid-spring-boot-starter</artifactId>
  33. <version>${druid.version}</version>
  34. </dependency>
  35. <dependency>
  36. <groupId>com.baomidou</groupId>
  37. <artifactId>mybatis-plus-boot-starter</artifactId>
  38. <version>${mybatis-plus.version}</version>
  39. </dependency>
  40. <!--mybatis-plus代码生成器相关依赖-->
  41. <dependency>
  42. <groupId>com.baomidou</groupId>
  43. <artifactId>mybatis-plus-generator</artifactId>
  44. <version>${mybatis-plus.version}</version>
  45. </dependency>
  46. <dependency>
  47. <groupId>org.freemarker</groupId>
  48. <artifactId>freemarker</artifactId>
  49. <version>${freemarker.version}</version>
  50. </dependency>
  51. <dependency>
  52. <groupId>org.apache.commons</groupId>
  53. <artifactId>commons-lang3</artifactId>
  54. <version>${commons-lang3.version}</version>
  55. </dependency>
  56. <dependency>
  57. <groupId>org.projectlombok</groupId>
  58. <artifactId>lombok</artifactId>
  59. <version>${lombok.version}</version>
  60. </dependency>
  61. <dependency>
  62. <groupId>org.springframework.boot</groupId>
  63. <artifactId>spring-boot-starter-test</artifactId>
  64. <scope>test</scope>
  65. </dependency>
  66. </dependencies>
  67. <build>
  68. <plugins>
  69. <plugin>
  70. <groupId>org.springframework.boot</groupId>
  71. <artifactId>spring-boot-maven-plugin</artifactId>
  72. </plugin>
  73. </plugins>
  74. </build>

代码生成器使用示例:

  1. //执行 main 方法,控制台输入模块表名,回车自动生成对应项目目录中
  2. public class MybatisPlusCodeGenerator {
  3. public static void main(String[] args) {
  4. //====================配置变量区域=====================//
  5. String author="";//生成文件的作者,可以不填
  6. String rootPackage="org.example.xxxx";//生成的entity、controller、service等包所在的公共上一级包路径全限定名
  7. String moduleName="province-sess-platfrom-xqxy";
  8. //数据库配置
  9. String url="jdbc:mysql://192.168.xxx.xxx:3306/xxx?useSSL=false&characterEncoding=utf8";
  10. String driverClassName="com.mysql.jdbc.Driver";//或者com.mysql.cj.jdbc.Driver
  11. String username="root";
  12. String password="xxxxxx";
  13. String tableNames="annualplan";//表名,多个使用,分隔
  14. //====================配置变量区域=====================//
  15. // 代码生成器
  16. AutoGenerator generator = new AutoGenerator();
  17. // 全局配置
  18. GlobalConfig globalConfig = new GlobalConfig();
  19. String projectPath = System.getProperty("user.dir");
  20. globalConfig.setOutputDir(projectPath +"/"+moduleName+"/src/main/java");
  21. globalConfig.setFileOverride(false);//是否覆盖已有文件,默认false
  22. globalConfig.setOpen(false);//是否打开输出目录
  23. globalConfig.setAuthor(author);
  24. globalConfig.setServiceName("%sService");//去掉service接口的首字母I
  25. globalConfig.setBaseResultMap(true);//开启 BaseResultMap
  26. globalConfig.setDateType(DateType.ONLY_DATE);//只使用 java.util.date代替
  27. globalConfig.setIdType(IdType.ASSIGN_ID);//分配ID (主键类型为number或string)
  28. generator.setGlobalConfig(globalConfig);
  29. // 数据源配置
  30. DataSourceConfig dataSourceConfig = new DataSourceConfig();
  31. dataSourceConfig.setUrl(url);
  32. dataSourceConfig.setDbType(DbType.MYSQL);//数据库类型
  33. dataSourceConfig.setDriverName(driverClassName);
  34. dataSourceConfig.setUsername(username);
  35. dataSourceConfig.setPassword(password);
  36. generator.setDataSource(dataSourceConfig);
  37. // 包配置
  38. PackageConfig packageConfig = new PackageConfig();
  39. //packageConfig.setModuleName(scanner("模块名"));
  40. packageConfig.setParent(rootPackage);//例:org.jeecg.modules.xqxy
  41. generator.setPackageInfo(packageConfig);
  42. //注意:模板引擎在mybatisplus依赖中的templates目录下,可以依照此默认模板进行自定义
  43. // 策略配置:配置根据哪张表生成代码
  44. StrategyConfig strategy = new StrategyConfig();
  45. strategy.setInclude(tableNames);//表名,多个英文逗号分割(与exclude二选一配置)
  46. strategy.setNaming(NamingStrategy.underline_to_camel);
  47. strategy.setColumnNaming(NamingStrategy.underline_to_camel);
  48. //strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!");
  49. strategy.setEntityLombokModel(true);//lombok模型,@Accessors(chain = true)setter链式操作
  50. strategy.setRestControllerStyle(true);//controller生成@RestController
  51. strategy.setEntityTableFieldAnnotationEnable(true);//是否生成实体时,生成字段注解
  52. generator.setStrategy(strategy);
  53. generator.setTemplateEngine(new FreemarkerTemplateEngine());
  54. generator.execute();
  55. }
  56. }

详细配置可以在idea中查看配置类注释,download source,里面的注释都是中文的,比较详细。

 模板引擎在mybatisplus依赖中的templates目录下,可以依照此默认模板进行自定义:

controller.java.ftl:

  1. package ${package.Controller};
  2. import org.springframework.web.bind.annotation.RequestMapping;
  3. <#if restControllerStyle>
  4. import org.springframework.web.bind.annotation.RestController;
  5. <#else>
  6. import org.springframework.stereotype.Controller;
  7. </#if>
  8. <#if superControllerClassPackage??>
  9. import ${superControllerClassPackage};
  10. </#if>
  11. /**
  12. * <p>
  13. * ${table.comment!} 前端控制器
  14. * </p>
  15. *
  16. * @author ${author}
  17. * @since ${date}
  18. */
  19. <#if restControllerStyle>
  20. @RestController
  21. <#else>
  22. @Controller
  23. </#if>
  24. @RequestMapping("<#if package.ModuleName?? && package.ModuleName != "">/${package.ModuleName}</#if>/<#if controllerMappingHyphenStyle??>${controllerMappingHyphen}<#else>${table.entityPath}</#if>")
  25. <#if kotlin>
  26. class ${table.controllerName}<#if superControllerClass??> : ${superControllerClass}()</#if>
  27. <#else>
  28. <#if superControllerClass??>
  29. public class ${table.controllerName} extends ${superControllerClass} {
  30. <#else>
  31. public class ${table.controllerName} {
  32. </#if>
  33. }
  34. </#if>

entity.java.ftl:

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

mapper.java.ftl:

  1. package ${package.Mapper};
  2. import ${package.Entity}.${entity};
  3. import ${superMapperClassPackage};
  4. /**
  5. * <p>
  6. * ${table.comment!} Mapper 接口
  7. * </p>
  8. *
  9. * @author ${author}
  10. * @since ${date}
  11. */
  12. <#if kotlin>
  13. interface ${table.mapperName} : ${superMapperClass}<${entity}>
  14. <#else>
  15. public interface ${table.mapperName} extends ${superMapperClass}<${entity}> {
  16. }
  17. </#if>

mapper.xml.ftl:

  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. </#if>
  8. <#if baseResultMap>
  9. <!-- 通用查询映射结果 -->
  10. <resultMap id="BaseResultMap" type="${package.Entity}.${entity}">
  11. <#list table.fields as field>
  12. <#if field.keyFlag><#--生成主键排在第一位-->
  13. <id column="${field.name}" property="${field.propertyName}" />
  14. </#if>
  15. </#list>
  16. <#list table.commonFields as field><#--生成公共字段 -->
  17. <result column="${field.name}" property="${field.propertyName}" />
  18. </#list>
  19. <#list table.fields as field>
  20. <#if !field.keyFlag><#--生成普通字段 -->
  21. <result column="${field.name}" property="${field.propertyName}" />
  22. </#if>
  23. </#list>
  24. </resultMap>
  25. </#if>
  26. <#if baseColumnList>
  27. <!-- 通用查询结果列 -->
  28. <sql id="Base_Column_List">
  29. <#list table.commonFields as field>
  30. ${field.columnName},
  31. </#list>
  32. ${table.fieldNames}
  33. </sql>
  34. </#if>
  35. </mapper>

service.java.ftl:

  1. package ${package.Service};
  2. import ${package.Entity}.${entity};
  3. import ${superServiceClassPackage};
  4. /**
  5. * <p>
  6. * ${table.comment!} 服务类
  7. * </p>
  8. *
  9. * @author ${author}
  10. * @since ${date}
  11. */
  12. <#if kotlin>
  13. interface ${table.serviceName} : ${superServiceClass}<${entity}>
  14. <#else>
  15. public interface ${table.serviceName} extends ${superServiceClass}<${entity}> {
  16. }
  17. </#if>

serviceImpl.java.ftl:

  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 org.springframework.stereotype.Service;
  7. /**
  8. * <p>
  9. * ${table.comment!} 服务实现类
  10. * </p>
  11. *
  12. * @author ${author}
  13. * @since ${date}
  14. */
  15. @Service
  16. <#if kotlin>
  17. open class ${table.serviceImplName} : ${superServiceImplClass}<${table.mapperName}, ${entity}>(), ${table.serviceName} {
  18. }
  19. <#else>
  20. public class ${table.serviceImplName} extends ${superServiceImplClass}<${table.mapperName}, ${entity}> implements ${table.serviceName} {
  21. }
  22. </#if>

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/231095
推荐阅读
相关标签
  

闽ICP备14008679号