经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 数据库/运维 » MyBatis » 查看文章
SpringBoot整合MybatisPlus的简单教程实现(简单整合)
来源:jb51  时间:2019/5/16 9:00:27  对本文有异议

最近在研究springboot,顺便就会看看数据库连接这一块的知识 ,所以当我发现有通用Mapper和MybatisPlus这两款网络上比较火的简化mybatis开发的优秀软件之后。就都想试一下,看看哪一款比较适合自己。

先创建一个springboot的项目,可以参考我之前的文章Spring Boot 的简单教程(一) Spring Boot 项目的创建

创建好springboot之后就需要整合mybatis和mybatis-plus了。

打开pom.xml文件,将最新的mybatis相关的包都引用进来。

  1. <!-- 这是mysql的依赖 -->
  2. <dependency>
  3. <groupId>mysql</groupId>
  4. <artifactId>mysql-connector-java</artifactId>
  5. <scope>runtime</scope>
  6. </dependency>
  7. <!-- 这是lombok的依赖 -->
  8. <dependency>
  9. <groupId>org.projectlombok</groupId>
  10. <artifactId>lombok</artifactId>
  11. <optional>true</optional>
  12. </dependency>
  13. <!-- 这是mybatis-plus依赖 -->
  14. <dependency>
  15. <groupId>com.baomidou</groupId>
  16. <artifactId>mybatis-plus-boot-starter</artifactId>
  17. <version>3.1.1</version>
  18. </dependency>
  19. <!-- 这是mybatis-plus的代码自动生成器 -->
  20. <dependency>
  21. <groupId>com.baomidou</groupId>
  22. <artifactId>mybatis-plus-generator</artifactId>
  23. <version>3.1.1</version>
  24. </dependency>
  25. <!-- 这是模板引擎依赖 -->
  26. <dependency>
  27. <groupId>org.freemarker</groupId>
  28. <artifactId>freemarker</artifactId>
  29. <version>2.3.28</version>
  30. </dependency>

需要对application.yml进行相关的配置。

  1. #端口号
  2. server:
  3. port: 8088
  4. #数据库的配置信息
  5. spring:
  6. datasource:
  7. url: jdbc:mysql://localhost:3306/*** #自己的数据库名称
  8. username: root
  9. password: 123456
  10. mybatis:
  11. #开启驼峰命名法
  12. configuration:
  13. map-underscore-to-camel-case: true
  14. mybatis-plus:
  15. # xml地址
  16. mapper-locations: classpath:mapper/*Mapper.xml
  17. # 实体扫描,多个package用逗号或者分号分隔
  18. type-aliases-package: *** #自己的实体类地址
  19. configuration:
  20. # 这个配置会将执行的sql打印出来,在开发或测试的时候可以用
  21. log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

自动生成模块的方法,在相应的位置上添加上自己的一些包名就可以运行生成相应的Entity、Mapper、Mapper XML、Service、Controller 等各个模块的代码。

  1. public class CodeGenerator {
  2.  
  3. /**
  4. * <p>
  5. * 读取控制台内容
  6. * </p>
  7. */
  8. public static String scanner(String tip) {
  9. Scanner scanner = new Scanner(System.in);
  10. StringBuilder help = new StringBuilder();
  11. help.append("请输入" + tip + ":");
  12. System.out.println(help.toString());
  13. if (scanner.hasNext()) {
  14. String ipt = scanner.next();
  15. if (StringUtils.isNotEmpty(ipt)) {
  16. return ipt;
  17. }
  18. }
  19. throw new MybatisPlusException("请输入正确的" + tip + "!");
  20. }
  21.  
  22. public static void main(String[] args) {
  23. // 代码生成器
  24. AutoGenerator mpg = new AutoGenerator();
  25. // 全局配置
  26. GlobalConfig gc = new GlobalConfig();
  27. String projectPath = System.getProperty("user.dir");
  28. gc.setOutputDir(projectPath + "/src/main/java");
  29. gc.setAuthor("jobob");
  30. gc.setOpen(false);
  31. // gc.setSwagger2(true); 实体属性 Swagger2 注解
  32. mpg.setGlobalConfig(gc);
  33.  
  34. // 数据源配置
  35. DataSourceConfig dsc = new DataSourceConfig();
  36. dsc.setUrl("jdbc:mysql://localhost:3306/***?useUnicode=true&useSSL=false&characterEncoding=utf8");
  37. // dsc.setSchemaName("public");
  38. dsc.setDriverName("com.mysql.cj.jdbc.Driver");
  39. dsc.setUsername("root");
  40. dsc.setPassword("***");
  41. mpg.setDataSource(dsc);
  42.  
  43. // 包配置
  44. PackageConfig pc = new PackageConfig();
  45. //这里有个模块名的配置,可以注释掉不用。
  46. // pc.setModuleName(scanner("模块名"));
  47. pc.setParent("com.zhouxiaoxi.www");
  48. mpg.setPackageInfo(pc);
  49.  
  50. // 自定义配置
  51. InjectionConfig cfg = new InjectionConfig() {
  52. @Override
  53. public void initMap() {
  54. // to do nothing
  55. }
  56. };
  57.  
  58. // 如果模板引擎是 freemarker
  59. String templatePath = "/templates/mapper.xml.ftl";
  60. // 如果模板引擎是 velocity
  61. // String templatePath = "/templates/mapper.xml.vm";
  62.  
  63. // 自定义输出配置
  64. List<FileOutConfig> focList = new ArrayList<>();
  65. // 自定义配置会被优先输出
  66. focList.add(new FileOutConfig(templatePath) {
  67. @Override
  68. public String outputFile(TableInfo tableInfo) {
  69. // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
  70. return projectPath + "/src/main/resources/mapper/"
  71. // + + pc.getModuleName() + 如果放开上面的模块名,这里就有一个模块名了
  72. + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
  73. }
  74. });
  75. /*
  76. cfg.setFileCreate(new IFileCreate() {
  77. @Override
  78. public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
  79. // 判断自定义文件夹是否需要创建
  80. checkDir("调用默认方法创建的目录");
  81. return false;
  82. }
  83. });
  84. */
  85. cfg.setFileOutConfigList(focList);
  86. mpg.setCfg(cfg);
  87.  
  88. // 配置模板
  89. TemplateConfig templateConfig = new TemplateConfig();
  90.  
  91. // 配置自定义输出模板
  92. //指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
  93. // templateConfig.setEntity("templates/entity2.java");
  94. // templateConfig.setService();
  95. // templateConfig.setController();
  96.  
  97. templateConfig.setXml(null);
  98. mpg.setTemplate(templateConfig);
  99.  
  100. // 策略配置
  101. StrategyConfig strategy = new StrategyConfig();
  102. //数据库表映射到实体的明明策略
  103. strategy.setNaming(NamingStrategy.underline_to_camel);
  104. //数据库表字段映射到实体的命名策略, 未指定按照 naming 执行
  105. strategy.setColumnNaming(NamingStrategy.underline_to_camel);
  106. //自定义继承的Entity类全称,带包名
  107. // strategy.setSuperEntityClass("***");
  108. strategy.setEntityLombokModel(true);
  109. strategy.setRestControllerStyle(true);
  110. //自定义继承的Controller类全称,带包名
  111. // strategy.setSuperControllerClass("***");
  112. strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
  113. //自定义基础的Entity类,公共字段(可添加更多)
  114. // strategy.setSuperEntityColumns("id");
  115. //驼峰转连字符
  116. strategy.setControllerMappingHyphenStyle(true);
  117. //表前缀
  118. // strategy.setTablePrefix(pc.getModuleName() + "_");
  119. mpg.setStrategy(strategy);
  120. mpg.setTemplateEngine(new FreemarkerTemplateEngine());
  121. mpg.execute();
  122. }
  123.  
  124. }

在生成的controller里面添加对应的方法启动就可以正常进行访问了。

当然还需要在 Spring Boot 启动类中添加 @MapperScan 注解,扫描 Mapper 文件夹:

  1. @SpringBootApplication
  2. @MapperScan("***.*.mapper") //对应你的mapper存放的地址
  3. public class Application {
  4.  
  5. public static void main(String[] args) {
  6. SpringApplication.run(QuickStartApplication.class, args);
  7. }
  8.  
  9. }

 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持w3xue。

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号