当前位置:   article > 正文

Springboot集成mybatis-plus自动生成代码

springboot集成mybatis-plus自动生成代码

一、mybatis-Plus介绍

        Mybatis-Plus(以下简称MP)是Mybatis的增强工具(MBG和通用Mapper可看成插件),在Mybatis的基础上增加了很多功能,简化开发,提高效率。、

二、mybatis-plus集成

       1.在pom.xml文件中添加依赖

  1. <!-- mybatis-plus-generator代码生成器依赖-->
  2. <dependency>
  3. <groupId>com.baomidou</groupId>
  4. <artifactId>mybatis-plus-generator</artifactId>
  5. <version>3.3.2</version>
  6. </dependency>

        2.创建CodeGenerator.java文件

  1. package com.hng.business;
  2. import ch.qos.logback.core.net.SyslogOutputStream;
  3. import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
  4. import com.baomidou.mybatisplus.core.toolkit.StringPool;
  5. import com.baomidou.mybatisplus.core.toolkit.StringUtils;
  6. import com.baomidou.mybatisplus.generator.AutoGenerator;
  7. import com.baomidou.mybatisplus.generator.InjectionConfig;
  8. import com.baomidou.mybatisplus.generator.config.*;
  9. import com.baomidou.mybatisplus.generator.config.po.TableInfo;
  10. import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
  11. import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
  12. import java.util.ArrayList;
  13. import java.util.List;
  14. import java.util.Scanner;
  15. /**
  16. * @Author 郝南过
  17. * @Date 2023/11/6 16:30
  18. * @Version 1.0
  19. * mybatis-plus代码生成器官网地址 https://baomidou.com/pages/d357af/
  20. */
  21. public class CodeGenerator {
  22. // 数据库连接字段配置
  23. private static final String JDBC_URL = "jdbc:mysql://xxx.xxx.xxx.xxx:3306/hng?useUnicode=true&useSSL=false&characterEncoding=utf8";
  24. private static final String JDBC_USER_NAME = "root";
  25. private static final String JDBC_PASSWORD = "xxxxx";
  26. // 包名和模块名
  27. private static final String PACKAGE_NAME = "com.hng";
  28. private static final String MODULE_NAME = "business";
  29. // 表名,多个表使用英文逗号分割
  30. private static final String[] TBL_NAMES = {"student", "subject", "sheet"};
  31. // 表名的前缀,从表生成代码时会去掉前缀
  32. private static final String TABLE_PREFIX = "tbl_";
  33. /**
  34. * <p>
  35. * 读取控制台内容 控制台输入模块表名回车自动生成对应项目目录中
  36. * </p>
  37. */
  38. public static String scanner(String tip) {
  39. Scanner scanner = new Scanner(System.in);
  40. StringBuilder help = new StringBuilder();
  41. help.append("请输入" + tip + ":");
  42. System.out.println(help.toString());
  43. if (scanner.hasNext()) {
  44. String ipt = scanner.next();
  45. if (StringUtils.isNotBlank(ipt)) {
  46. return ipt;
  47. }
  48. }
  49. throw new MybatisPlusException("请输入正确的" + tip + "!");
  50. }
  51. public static void main(String[] args) {
  52. // 代码生成器
  53. AutoGenerator mpg = new AutoGenerator();
  54. // 全局配置
  55. GlobalConfig gc = new GlobalConfig();
  56. String projectPath = System.getProperty("user.dir")+"/"+MODULE_NAME;
  57. gc.setOutputDir(projectPath + "/src/main/java");
  58. gc.setAuthor("郝南过");
  59. gc.setOpen(false);
  60. //实体属性 Swagger2 注解
  61. gc.setSwagger2(true);
  62. //再次调用时是否覆盖原文件
  63. //gc.setFileOverride(true);
  64. //去掉Service接口自动生成的首字母I
  65. gc.setServiceName("%sService");
  66. mpg.setGlobalConfig(gc);
  67. // 数据源配置
  68. DataSourceConfig dsc = new DataSourceConfig();
  69. //只需要把moon_light修改为你自己的数据库即可
  70. dsc.setUrl(JDBC_URL);
  71. // dsc.setSchemaName("public");
  72. dsc.setDriverName("com.mysql.cj.jdbc.Driver");
  73. dsc.setUsername(JDBC_USER_NAME);
  74. dsc.setPassword(JDBC_PASSWORD);
  75. mpg.setDataSource(dsc);
  76. // 包配置
  77. PackageConfig pc = new PackageConfig();
  78. //pc.setModuleName(scanner("模块名"));
  79. pc.setModuleName(MODULE_NAME);
  80. //你的项目包结构名
  81. pc.setParent(PACKAGE_NAME);
  82. mpg.setPackageInfo(pc);
  83. // 自定义配置
  84. InjectionConfig cfg = new InjectionConfig() {
  85. @Override
  86. public void initMap() {
  87. // to do nothing
  88. }
  89. };
  90. // 如果模板引擎是 freemarker
  91. String templatePath = "/templates/mapper.xml.ftl";
  92. // 如果模板引擎是 velocity
  93. // String templatePath = "/templates/mapper.xml.vm";
  94. // 自定义输出配置
  95. List<FileOutConfig> focList = new ArrayList<>();
  96. // 自定义配置会被优先输出
  97. focList.add(new FileOutConfig(templatePath) {
  98. @Override
  99. public String outputFile(TableInfo tableInfo) {
  100. // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
  101. // ( pc.getModuleName()如果前面设置了null,这里应该不写)
  102. //return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()
  103. return projectPath + "/src/main/resources/mapper/"
  104. + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
  105. }
  106. });
  107. /*
  108. cfg.setFileCreate(new IFileCreate() {
  109. @Override
  110. public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
  111. // 判断自定义文件夹是否需要创建
  112. checkDir("调用默认方法创建的目录,自定义目录用");
  113. if (fileType == FileType.MAPPER) {
  114. // 已经生成 mapper 文件判断存在,不想重新生成返回 false
  115. return !new File(filePath).exists();
  116. }
  117. // 允许生成模板文件
  118. return true;
  119. }
  120. });
  121. */
  122. cfg.setFileOutConfigList(focList);
  123. mpg.setCfg(cfg);
  124. // 配置模板
  125. TemplateConfig templateConfig = new TemplateConfig();
  126. // 配置自定义输出模板
  127. //指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
  128. // templateConfig.setEntity("templates/entity2.java");
  129. // templateConfig.setService();
  130. // templateConfig.setController();
  131. templateConfig.setXml(null);
  132. mpg.setTemplate(templateConfig);
  133. // 策略配置
  134. StrategyConfig strategy = new StrategyConfig();
  135. //数据库表映射到实体的命名策略
  136. strategy.setNaming(NamingStrategy.underline_to_camel);
  137. //数据库表字段映射到实体的命名策略
  138. strategy.setColumnNaming(NamingStrategy.underline_to_camel);
  139. //strategy.setSuperEntityClass("你自己的父类实体,没有就不用设置!");
  140. strategy.setEntityLombokModel(true);
  141. strategy.setRestControllerStyle(true);
  142. // 公共父类
  143. //strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");
  144. // 写于父类中的公共字段
  145. strategy.setSuperEntityColumns("id");
  146. strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
  147. strategy.setControllerMappingHyphenStyle(true);
  148. //生成实体类等时去掉表前缀
  149. //strategy.setTablePrefix("m_"); //(没有前缀就只写_)
  150. strategy.setTablePrefix(pc.getModuleName() + "_");
  151. mpg.setStrategy(strategy);
  152. mpg.setTemplateEngine(new FreemarkerTemplateEngine());
  153. mpg.execute();
  154. }
  155. }

       3.运行CodeGenerator.java中的main()方法即可生成对应的Controller、service、serviceImpl、mapper注意mapper文件上默认没有注解@Repository)、mapper.xml、entity文件。且可以开启swagger注解,便于在swagger中查看和调试。

三、mybatis-plus使用

        生成的mapper.xml为空,默认方法都baseMapper中,可在ServiceImpl中直接使用baseMapper进行调用使用,且提供了大量基础常用的方法。包括分页等。

【具体详细的使用可参考官方文档】:https://baomidou.com/pages/d357af/

 

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

闽ICP备14008679号