Mybatis——》mybatis-plus-generator代码生成器

- 日理万妓 2024-04-08 09:04 207阅读 0赞

推荐链接:
总结——》【Java】
总结——》【Mysql】
总结——》【Spring】
总结——》【SpringBoot】
总结——》【MyBatis、MyBatis-Plus】

Mybatis——》mybatis-plus-generator代码生成器

  • 一、数据库
  • 二、项目结构
  • 三、添加pom依赖
  • 四、创建代码生成器类
    • 1、3.5.1以下版本
    • 2、3.5.1 及其以上版本
  • 五、执行main方法
  • 六、测试

https://gitee.com/xiaoxianwansui/springboot-mybatisplus-generator

一、数据库

  1. /*
  2. Schema:test
  3. Info:测试数据库
  4. Date:2022/09/07 13:49:38
  5. */
  6. -- 1、创建数据库
  7. CREATE
  8. DATABASE `xiaoxian` CHARACTER SET 'utf8' COLLATE 'utf8_general_ci';
  9. -- 2、创建表
  10. DROP TABLE IF EXISTS `user`;
  11. CREATE TABLE `user`
  12. (
  13. `id` bigint NOT NULL AUTO_INCREMENT,
  14. `name` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL,
  15. `version` int NOT NULL DEFAULT '0' COMMENT '乐观锁版本号',
  16. `is_delete` tinyint(1) NOT NULL DEFAULT '0' COMMENT '逻辑删除标识1:已删除,0:未删除',
  17. `create_user` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '创建用户',
  18. `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  19. `update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  20. `update_user` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '更新用户',
  21. PRIMARY KEY (`id`) USING BTREE
  22. ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb3 ROW_FORMAT=DYNAMIC;
  23. -- 3、插入数据
  24. INSERT INTO `xiaoxian`.`user` (`id`, `name`, `version`, `is_delete`, `create_user`, `create_time`, `update_time`,
  25. `update_user`)
  26. VALUES (1, '赵', 0, 0, 'system', '2022-08-16 13:44:57', '2022-08-16 13:45:11', 'system');
  27. INSERT INTO `xiaoxian`.`user` (`id`, `name`, `version`, `is_delete`, `create_user`, `create_time`, `update_time`,
  28. `update_user`)
  29. VALUES (2, '钱', 0, 0, 'system', '2022-08-16 13:44:57', '2022-08-16 13:45:11', 'system');
  30. INSERT INTO `xiaoxian`.`user` (`id`, `name`, `version`, `is_delete`, `create_user`, `create_time`, `update_time`,
  31. `update_user`)
  32. VALUES (3, '孙', 0, 0, 'system', '2022-08-16 13:44:57', '2022-08-16 13:45:11', 'system');
  33. INSERT INTO `xiaoxian`.`user` (`id`, `name`, `version`, `is_delete`, `create_user`, `create_time`, `update_time`,
  34. `update_user`)
  35. VALUES (4, '李', 0, 0, 'system', '2022-08-16 13:44:57', '2022-08-16 13:45:11', 'system');

二、项目结构

在这里插入图片描述

三、添加pom依赖

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <parent>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-parent</artifactId>
  8. <version>2.7.1</version>
  9. <relativePath/>
  10. </parent>
  11. <groupId>com.xiaoxian</groupId>
  12. <artifactId>mybatisplus-generator</artifactId>
  13. <version>0.0.1-SNAPSHOT</version>
  14. <name>generator</name>
  15. <description>springboot-mybatisplus-generator</description>
  16. <properties>
  17. <java.version>1.8</java.version>
  18. <druid.version>1.1.22</druid.version>
  19. <mybatis.plus.version>3.4.1</mybatis.plus.version>
  20. <!-- <mybatis.plus.version>3.5.1</mybatis.plus.version>-->
  21. <guava.version>28.2-jre</guava.version>
  22. <knife4j.version>2.0.8</knife4j.version>
  23. <fastjson.version>1.2.70</fastjson.version>
  24. </properties>
  25. <dependencies>
  26. <dependency>
  27. <groupId>org.springframework.boot</groupId>
  28. <artifactId>spring-boot-starter-web</artifactId>
  29. </dependency>
  30. <dependency>
  31. <groupId>org.springframework.boot</groupId>
  32. <artifactId>spring-boot-starter-jdbc</artifactId>
  33. </dependency>
  34. <dependency>
  35. <groupId>mysql</groupId>
  36. <artifactId>mysql-connector-java</artifactId>
  37. <scope>runtime</scope>
  38. </dependency>
  39. <dependency>
  40. <groupId>com.alibaba</groupId>
  41. <artifactId>druid-spring-boot-starter</artifactId>
  42. <version>${druid.version}</version>
  43. </dependency>
  44. <!-- mybatis-plus start-->
  45. <dependency>
  46. <groupId>com.baomidou</groupId>
  47. <artifactId>mybatis-plus-boot-starter</artifactId>
  48. <version>${mybatis.plus.version}</version>
  49. </dependency>
  50. <dependency>
  51. <groupId>com.baomidou</groupId>
  52. <artifactId>mybatis-plus</artifactId>
  53. <version>${mybatis.plus.version}</version>
  54. </dependency>
  55. <!-- mybatis-plus generator start-->
  56. <dependency>
  57. <groupId>com.baomidou</groupId>
  58. <artifactId>mybatis-plus-generator</artifactId>
  59. <version>${mybatis.plus.version}</version>
  60. </dependency>
  61. <dependency>
  62. <groupId>org.apache.velocity</groupId>
  63. <artifactId>velocity-engine-core</artifactId>
  64. <version>2.2</version>
  65. </dependency>
  66. <!--test start-->
  67. <dependency>
  68. <groupId>org.springframework.boot</groupId>
  69. <artifactId>spring-boot-starter-test</artifactId>
  70. <scope>test</scope>
  71. </dependency>
  72. <!--lombok start-->
  73. <dependency>
  74. <groupId>org.projectlombok</groupId>
  75. <artifactId>lombok</artifactId>
  76. <optional>true</optional>
  77. </dependency>
  78. <!-- swagger start -->
  79. <dependency>
  80. <groupId>com.google.guava</groupId>
  81. <artifactId>guava</artifactId>
  82. <version>${guava.version}</version>
  83. </dependency>
  84. <dependency>
  85. <groupId>com.github.xiaoymin</groupId>
  86. <artifactId>knife4j-spring-boot-starter</artifactId>
  87. <version>${knife4j.version}</version>
  88. </dependency>
  89. <dependency>
  90. <groupId>com.github.xiaoymin</groupId>
  91. <artifactId>knife4j-aggregation-spring-boot-starter</artifactId>
  92. <version>${knife4j.version}</version>
  93. </dependency>
  94. <!--fastjson start-->
  95. <dependency>
  96. <groupId>com.alibaba</groupId>
  97. <artifactId>fastjson</artifactId>
  98. <version>${fastjson.version}</version>
  99. </dependency>
  100. </dependencies>
  101. <build>
  102. </build>
  103. </project>

四、创建代码生成器类

1、3.5.1以下版本

3.4.1

  1. package com.xiaoxian.mybatisplusgenerator;
  2. import com.baomidou.mybatisplus.core.toolkit.StringPool;
  3. import com.baomidou.mybatisplus.generator.AutoGenerator;
  4. import com.baomidou.mybatisplus.generator.InjectionConfig;
  5. import com.baomidou.mybatisplus.generator.config.*;
  6. import com.baomidou.mybatisplus.generator.config.builder.ConfigBuilder;
  7. import com.baomidou.mybatisplus.generator.config.po.TableInfo;
  8. import com.baomidou.mybatisplus.generator.config.rules.FileType;
  9. import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
  10. import lombok.extern.slf4j.Slf4j;
  11. import java.io.File;
  12. import java.util.ArrayList;
  13. import java.util.HashMap;
  14. import java.util.List;
  15. import java.util.Map;
  16. @Slf4j
  17. public class CodeGenerator {
  18. public static void generator(String projectPath, String projectName, String modulename, String mysqlUrl, String username, String password, String tableNams, String tablePrefix,
  19. String superEntityClass) {
  20. // 代码生成器
  21. AutoGenerator mpg = new AutoGenerator();
  22. modulename = modulename == null ? "" : modulename;
  23. // 全局配置
  24. GlobalConfig gc = new GlobalConfig();
  25. gc.setOutputDir("/src/main/java");
  26. gc.setFileOverride(true);
  27. gc.setActiveRecord(true);
  28. gc.setEnableCache(false);// XML 二级缓存
  29. gc.setBaseResultMap(true);// XML ResultMap
  30. gc.setBaseColumnList(true);// XML columList
  31. gc.setAuthor("xiaoxian");
  32. gc.setOpen(false);
  33. gc.setSwagger2(true);
  34. mpg.setGlobalConfig(gc);
  35. // 数据源配置
  36. DataSourceConfig dsc = new DataSourceConfig();
  37. dsc.setUrl("jdbc:mysql://" + mysqlUrl + "?autoReconnect=true&useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&zeroDateTimeBehavior=convertToNull&useSSL=false");
  38. dsc.setDriverName("com.mysql.jdbc.Driver");
  39. dsc.setUsername(username);
  40. dsc.setPassword(password);
  41. mpg.setDataSource(dsc);
  42. // 包配置
  43. PackageConfig pc = new PackageConfig();
  44. pc.setModuleName(modulename);
  45. pc.setParent("com.xiaoxian." + projectName);
  46. pc.setEntity("entity");
  47. pc.setXml("mapper");
  48. pc.setMapper("mapper");
  49. pc.setService("service");
  50. pc.setServiceImpl("service.impl");
  51. pc.setController("controller");
  52. Map<String, String> map = new HashMap();
  53. map.put(ConstVal.ENTITY_PATH, projectPath + gc.getOutputDir() + "/com/xiaoxian/" + "/" + projectName + modulename + "/entity");
  54. map.put(ConstVal.SERVICE_PATH, projectPath + gc.getOutputDir() + "/com/xiaoxian/" + "/" + projectName + modulename + "/service");
  55. map.put(ConstVal.SERVICE_IMPL_PATH, projectPath + gc.getOutputDir() + "/com/xiaoxian/" + projectName + "/" + modulename + "/service/impl");
  56. map.put(ConstVal.MAPPER_PATH, projectPath + gc.getOutputDir() + "/com/xiaoxian/" + "/" + projectName + modulename + "/mapper");
  57. map.put(ConstVal.XML_PATH, projectPath + "/src/main/resources/mapper");
  58. map.put(ConstVal.CONTROLLER_PATH, projectPath + gc.getOutputDir() + "/com/xiaoxian/" + "/" + projectName + modulename + "/controller");
  59. pc.setPathInfo(map);
  60. mpg.setPackageInfo(pc);
  61. // 自定义配置
  62. InjectionConfig cfg = new InjectionConfig() {
  63. @Override
  64. public void initMap() {
  65. // to do nothing
  66. }
  67. };
  68. // 如果模板引擎是 freemarker
  69. // String templatePath = "/templates/mapper.xml.ftl";
  70. // 如果模板引擎是 velocity
  71. String templatePath = "/templates/mapper.xml.vm";
  72. // 自定义输出配置
  73. List<FileOutConfig> focList = new ArrayList<>();
  74. // 自定义配置会被优先输出
  75. focList.add(new FileOutConfig(templatePath) {
  76. @Override
  77. public String outputFile(TableInfo tableInfo) {
  78. // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
  79. return projectPath + "/src/main/resources/mapper/"
  80. + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
  81. }
  82. });
  83. cfg.setFileCreate(new IFileCreate() {
  84. @Override
  85. public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
  86. // 判断自定义文件夹是否需要创建
  87. checkDir(filePath);
  88. if (fileType == FileType.MAPPER) {
  89. // 已经生成 mapper 文件判断存在,不想重新生成返回 false
  90. return !new File(filePath).exists();
  91. }
  92. // 允许生成模板文件
  93. return true;
  94. }
  95. });
  96. cfg.setFileOutConfigList(focList);
  97. mpg.setCfg(cfg);
  98. // 配置模板
  99. TemplateConfig templateConfig = new TemplateConfig();
  100. // 配置自定义输出模板
  101. //指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
  102. // templateConfig.setEntity("templates/entity2.java");
  103. // templateConfig.setService();
  104. // templateConfig.setController();
  105. templateConfig.setXml(null);
  106. mpg.setTemplate(templateConfig);
  107. // 策略配置
  108. StrategyConfig strategy = new StrategyConfig();
  109. strategy.setNaming(NamingStrategy.underline_to_camel);
  110. strategy.setColumnNaming(NamingStrategy.underline_to_camel);
  111. strategy.setSuperEntityClass(superEntityClass);
  112. strategy.setEntityLombokModel(true);
  113. strategy.setRestControllerStyle(true);
  114. // 公共父类
  115. // strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");
  116. // 写于父类中的公共字段
  117. strategy.setSuperEntityColumns("id", "version", "is_delete", "create_time", "update_time", "update_user", "create_user");
  118. strategy.setInclude(tableNams.split(","));
  119. strategy.setControllerMappingHyphenStyle(true);
  120. strategy.setTablePrefix(tablePrefix);
  121. mpg.setStrategy(strategy);
  122. // mpg.setTemplateEngine(new FreemarkerTemplateEngine());
  123. mpg.execute();
  124. }
  125. public static void main(String[] args) {
  126. //生成在当前项目路径
  127. String projectPath = System.getProperty("user.dir");
  128. generator(
  129. projectPath,
  130. "mybatisplusgenerator",
  131. "",
  132. "127.0.0.1:3306/test",
  133. "root",
  134. "123456",
  135. "user",
  136. "t_",
  137. "com.xiaoxian.mybatisplusgenerator.common.BaseEntity"
  138. );
  139. }
  140. }

2、3.5.1 及其以上版本

3.5.1

  1. package com.xiaoxian.mybatisplusgenerator;
  2. import com.baomidou.mybatisplus.generator.FastAutoGenerator;
  3. import com.baomidou.mybatisplus.generator.config.OutputFile;
  4. import lombok.extern.slf4j.Slf4j;
  5. import java.util.HashMap;
  6. import java.util.Map;
  7. @Slf4j
  8. public class CodeGeneratorNew {
  9. public static void generator(String projectPath, String projectName, String modulename, String mysqlUrl, String username, String password, String tableNams, String tablePrefix,
  10. String superEntityClass) {
  11. String javaDir = projectPath + "/src/main/java";
  12. String resourcesDir = projectPath + "/src/main/resources";
  13. Map<OutputFile, String> map = new HashMap();
  14. map.put(OutputFile.entity, javaDir + "/com/xiaoxian/" + "/" + projectName + modulename + "/entity");
  15. map.put(OutputFile.service, javaDir + "/com/xiaoxian/" + "/" + projectName + modulename + "/service");
  16. map.put(OutputFile.serviceImpl, javaDir + "/com/xiaoxian/" + projectName + "/" + modulename + "/service/impl");
  17. map.put(OutputFile.mapper, javaDir + "/com/xiaoxian/" + "/" + projectName + modulename + "/mapper");
  18. map.put(OutputFile.mapperXml, resourcesDir + "/mapper");
  19. map.put(OutputFile.controller, javaDir + "/com/xiaoxian/" + "/" + projectName + modulename + "/controller");
  20. FastAutoGenerator.create("jdbc:mysql://" + mysqlUrl + "?autoReconnect=true&useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&zeroDateTimeBehavior=convertToNull&useSSL=false", username, password)
  21. .globalConfig(builder -> {
  22. builder.author("xiaoxiao") // 设置作者
  23. .enableSwagger() // 开启 swagger 模式
  24. .fileOverride() // 覆盖已生成文件
  25. .outputDir(javaDir); // 指定输出目录
  26. })
  27. .packageConfig(builder -> {
  28. builder.parent("com.xiaoxian.mybatisplusgenerator") // 设置父包名
  29. .entity("entity")
  30. .mapper("mapper")
  31. .moduleName("") // 设置父包模块名
  32. .pathInfo(map); // 设置mapperXml生成路径
  33. })
  34. .strategyConfig(builder -> {
  35. builder.addInclude("user") // 设置需要生成的表名
  36. .addTablePrefix("cms_", "c_") // 设置过滤表前缀
  37. .entityBuilder().enableLombok().enableChainModel().enableActiveRecord().superClass(superEntityClass)
  38. ;
  39. })
  40. // .templateEngine(new FreemarkerTemplateEngine()) // 使用Freemarker引擎模板,默认的是Velocity引擎模板
  41. .execute();
  42. }
  43. public static void main(String[] args) {
  44. //生成在当前项目路径
  45. String projectPath = System.getProperty("user.dir");
  46. generator(
  47. projectPath,
  48. "mybatisplusgenerator",
  49. "",
  50. "127.0.0.1:3306/xiaoxian",
  51. "root",
  52. "123456",
  53. "user",
  54. "t_",
  55. "com.xiaoxian.mybatisplusgenerator.common.BaseEntity"
  56. );
  57. }
  58. }

五、执行main方法

在这里插入图片描述

六、测试

  1. package com.xiaoxian.mybatisplusgenerator;
  2. import com.xiaoxian.mybatisplusgenerator.service.IUserService;
  3. import org.junit.jupiter.api.Test;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.boot.test.context.SpringBootTest;
  6. @SpringBootTest
  7. class ApplicationTests {
  8. @Autowired
  9. IUserService userService;
  10. @Test
  11. void list() {
  12. System.out.println(userService.list());
  13. }
  14. }

在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,207人围观)

还没有评论,来说两句吧...

相关阅读

    相关 代码生成器

    如果你是一名后端开发者,那么大多数的工作一定是重复编写各种 CRUD(增删改查)代码。时间长了你会发现,这些工作不仅无趣,还会浪费你的很多时间,没有机会去做更有创造力和挑战的工