相关推荐recommended
SpringBoot(3)整合MyBatis 和MybatisPlus
作者:mmseoamin日期:2023-12-13

SpringBoot(3)整合MyBatis 和MybatisPlus

    • 1.整合MyBatis
      • 1.1新建模块
      • 1.2在pom.xml中添加mysql驱动
        • 1.2.1防止编译时不将静态资源编译进去,在pom.xml中添加
        • 1.3.application.yml中添加内容
        • 1.2.resources中添加generatorConfig.xml
        • 1.3在pom中添加插件
        • 1.4测试
        • 1.5.新建一个controller包,添加JdbcController
        • 1.6启动项目
        • 2.整合MybatisPlus
          • 2.1添加依赖
          • 2.2添加MyBatis配置类
          • 2.3启动配置类
          • 2.4发现一个问题,MyBatisPlus自动生成的实体类没有主键,已手动添加
          • 2.5然后测试一下查询接口,成功
          • 2.6MyBatisPlus使用多表联查
            • 2.6.1在UserService中添加
            • 2.6.2在UserServiceImpl中添加
            • 2.6.3在UserMapper接口上添加
            • 2.6.5在UserController中添加
            • 2.6.6两表联查成功

              1.整合MyBatis

              1.1新建模块

              SpringBoot(3)整合MyBatis 和MybatisPlus,image-20230809133811383,第1张

              1.2在pom.xml中添加mysql驱动

              
                  mysql
                  mysql-connector-java
                  8.0.26
              
              
              1.2.1防止编译时不将静态资源编译进去,在pom.xml中添加
                     
                          
                              src/main/resources
                              
                                  *.properties
                                  *.xml
                                  *.yml
                                  **/*.xml
                              
                          
                      
              

              1.3.application.yml中添加内容

              jdbc.driver=com.mysql.cj.jdbc.Driver
              jdbc.url=jdbc:mysql://localhost:3306/crm?useUnicode=true&characterEncoding=UTF-8
              jdbc.username=root
              jdbc.password=123456
              

              1.2.resources中添加generatorConfig.xml

              
              
              
                  
                  
                  
              
                  
                  
                      
                      
                          
                           
                      
                      
                      
                      
                      
                          
                          
                      
                      
                      
                      
                      
                          
                          
                          
                          
                          
                          
                          
                          
                      
                      
                      
                          
                          
                      
                      
                      
                      
                      
                      
                          
                          
                      
                      
                      
                      
                      
                      
                      
                      
                      
                      
                      
                      
                      
                      
                      

              SpringBoot(3)整合MyBatis 和MybatisPlus,image-20230809213624464,第2张

              1.3在pom中添加插件

              
                  org.mybatis.generator
                  mybatis-generator-maven-plugin
                  1.3.2
                  
                      
                      
                          mysql
                          mysql-connector-java
                          8.0.26
                      
                  
                  
                      true
                  
              
              

              1.4测试

              SpringBoot(3)整合MyBatis 和MybatisPlus,image-20230809200750255,第3张

              SpringBoot(3)整合MyBatis 和MybatisPlus,image-20230809201234798,第4张

              1.5.新建一个controller包,添加JdbcController

              package com.hyx.springboot03.controller;
              import com.hyx.springboot03.mapper.CustomerMapper;
              import com.hyx.springboot03.model.Customer;
              import org.springframework.beans.factory.annotation.Autowired;
              import org.springframework.web.bind.annotation.*;
              @RestController
              @RequestMapping("/jdbc")
              public class JdbcController {
                  @Autowired
                  public CustomerMapper customerMapper;
                  @GetMapping("/get")
                  public Customer list(Integer cid) {
                      return customerMapper.selectByPrimaryKey(cid);
                  }
                  @DeleteMapping("/delete")
                  public int delete(Integer cid) {
                      return customerMapper.deleteByPrimaryKey(cid);
                  }
                  @PostMapping("/add")
                  public int add(Customer customer) {
                      return customerMapper.insertSelective(customer);
                  }
              }
              

              问题解决Could not autowire. No beans of ‘customerMapper‘ type found.

              SpringBoot(3)整合MyBatis 和MybatisPlus,image-20230809201637152,第5张

              还要修改启动类,在启动类上加上@mapperScan(“com.hyx.springboot03.mapper”)

              SpringBoot(3)整合MyBatis 和MybatisPlus,image-20230809214641760,第6张

              不然启动就会出现以下问题

              Field customerMapper in com.hyx.springboot03.controller.JdbcController required a bean of type 'com.hyx.springboot03.mapper.CustomerMapper' that could not be found.
              The injection point has the following annotations:
              	- @org.springframework.beans.factory.annotation.Autowired(required=true)
              Action:
              Consider defining a bean of type 'com.hyx.springboot03.mapper.CustomerMapper' in your configuration.
              

              SpringBoot(3)整合MyBatis 和MybatisPlus,image-20230809215249247,第7张

              好,当我们修改完成后

              1.6启动项目

              发送请求,成功返回数据

              SpringBoot(3)整合MyBatis 和MybatisPlus,image-20230809214438272,第8张

              SpringBoot(3)整合MyBatis 和MybatisPlus,image-20230809220726068,第9张

              2.整合MybatisPlus

              2.1添加依赖

              
                          com.baomidou
                          mybatis-plus-boot-starter
                          3.4.2
                      
                      
                          com.baomidou
                          mybatis-plus-generator
                          3.4.1
                      
                      
                          org.freemarker
                          freemarker
                          2.3.31
                      
              

              application.yml

              server:
                port: 8082
              spring:
                application:
                  name: springboot03
                datasource:
                  driver-class-name: com.mysql.cj.jdbc.Driver
                  url: jdbc:mysql://localhost:3306/crm?useUnicode=true&characterEncoding=UTF-8
                  password: 123456
                  username: root
              logging:
                level:
                  com.hyx.springboot03: debug
              mybatis-plus:
                mapper-locations: classpath:mappers/**/*.xml
                type-aliases-package: com.hyx.springboot03.model
              

              2.2添加MyBatis配置类

              package com.hyx.springboot03.mp;
              import com.baomidou.mybatisplus.annotation.DbType;
              import com.baomidou.mybatisplus.annotation.IdType;
              import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
              import com.baomidou.mybatisplus.core.toolkit.StringPool;
              import com.baomidou.mybatisplus.core.toolkit.StringUtils;
              import com.baomidou.mybatisplus.generator.AutoGenerator;
              import com.baomidou.mybatisplus.generator.InjectionConfig;
              import com.baomidou.mybatisplus.generator.config.*;
              import com.baomidou.mybatisplus.generator.config.po.TableInfo;
              import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
              import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
              import java.util.ArrayList;
              import java.util.List;
              import java.util.Scanner;
              /**
               * mybatis-plus代码生成
               */
              public class MPGenerator {
                  /**
                   * 

              * 读取控制台内容 *

              */ public static String scanner(String tip) { Scanner scanner = new Scanner(System.in); StringBuilder help = new StringBuilder(); help.append("请输入" + tip); System.out.println(help.toString()); if (scanner.hasNext()) { String ipt = scanner.next(); if (StringUtils.isNotBlank(ipt)) { if ("quit".equals(ipt)) return ""; return ipt; } } throw new MybatisPlusException("请输入正确的" + tip + "!"); } public static void main(String[] args) { // 代码生成器 AutoGenerator mpg = new AutoGenerator(); // 1.全局配置 GlobalConfig gc = new GlobalConfig(); String projectPath = System.getProperty("user.dir") + "/SpringBoot03"; System.out.println(projectPath); gc.setOutputDir(projectPath + "/src/main/java"); gc.setOpen(false); gc.setBaseResultMap(true);//生成BaseResultMap gc.setActiveRecord(false);// 不需要ActiveRecord特性的请改为false gc.setEnableCache(false);// XML 二级缓存 gc.setBaseResultMap(true);// XML ResultMap gc.setBaseColumnList(true);// XML columList //gc.setSwagger2(true); //实体属性 Swagger2 注解 gc.setAuthor("lky"); // 自定义文件命名,注意 %s 会自动填充表实体属性! gc.setMapperName("%sMapper"); gc.setXmlName("%sMapper"); gc.setServiceName("%sService"); gc.setServiceImplName("%sServiceImpl"); gc.setControllerName("%sController"); gc.setIdType(IdType.AUTO); mpg.setGlobalConfig(gc); // 2.数据源配置 DataSourceConfig dsc = new DataSourceConfig(); dsc.setDbType(DbType.MYSQL); dsc.setUrl("jdbc:mysql://localhost:3306/crm?useUnicode=true&characterEncoding=UTF-8"); dsc.setDriverName("com.mysql.cj.jdbc.Driver"); dsc.setUsername("root"); dsc.setPassword("123456"); mpg.setDataSource(dsc); // 3.包配置 PackageConfig pc = new PackageConfig(); String moduleName = scanner("模块名(quit退出,表示没有模块名)"); if (StringUtils.isNotBlank(moduleName)) { pc.setModuleName(moduleName); } pc.setParent("com.hyx.springboot03") .setMapper("mapper") .setService("service") .setController("controller") .setEntity("model"); mpg.setPackageInfo(pc); // 4.自定义配置 InjectionConfig cfg = new InjectionConfig() { @Override public void initMap() { // to do nothing } }; // 如果模板引擎是 freemarker String templatePath = "/templates/mapper.xml.ftl"; // 自定义输出配置 List focList = new ArrayList<>(); // 自定义配置会被优先输出 focList.add(new FileOutConfig(templatePath) { @Override public String outputFile(TableInfo tableInfo) { // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!! if (StringUtils.isNotBlank(pc.getModuleName())) { return projectPath + "/src/main/resources/mapper/" + pc.getModuleName() + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML; } else { return projectPath + "/src/main/resources/mapper/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML; } } }); cfg.setFileOutConfigList(focList); mpg.setCfg(cfg); // 配置模板 TemplateConfig templateConfig = new TemplateConfig(); templateConfig.setXml(null); mpg.setTemplate(templateConfig); // 5.策略配置 StrategyConfig strategy = new StrategyConfig(); // 表名生成策略(下划线转驼峰命名) strategy.setNaming(NamingStrategy.underline_to_camel); // 列名生成策略(下划线转驼峰命名) strategy.setColumnNaming(NamingStrategy.underline_to_camel); // 是否启动Lombok配置 strategy.setEntityLombokModel(true); // 是否启动REST风格配置 strategy.setRestControllerStyle(true); // 自定义实体父类strategy.setSuperEntityClass("com.baomidou.mybatisplus.extension.activerecord.Model"); // 自定义service父接口strategy.setSuperServiceClass("com.baomidou.mybatisplus.extension.service.IService"); // 自定义service实现类strategy.setSuperServiceImplClass("com.baomidou.mybatisplus.extension.service.impl.ServiceImpl"); // 自定义mapper接口strategy.setSuperMapperClass("com.baomidou.mybatisplus.core.mapper.BaseMapper"); strategy.setSuperEntityColumns("id"); // 写于父类中的公共字段plus strategy.setSuperEntityColumns("id"); strategy.setInclude(scanner("表名,多个英文逗号分割").split(",")); strategy.setControllerMappingHyphenStyle(true); //表名前缀(可变参数):“t_”或”“t_模块名”,例如:t_user或t_sys_user strategy.setTablePrefix("t_", "t_sys_"); //strategy.setTablePrefix(scanner("请输入表前缀")); mpg.setStrategy(strategy); mpg.setTemplateEngine(new FreemarkerTemplateEngine()); // 执行 mpg.execute(); } }

              2.3启动配置类

              SpringBoot(3)整合MyBatis 和MybatisPlus,image-20230809222717806,第10张

              SpringBoot(3)整合MyBatis 和MybatisPlus,image-20230809223437643,第11张

              2.4发现一个问题,MyBatisPlus自动生成的实体类没有主键,已手动添加

              SpringBoot(3)整合MyBatis 和MybatisPlus,image-20230809225440919,第12张

              2.5然后测试一下查询接口,成功

              SpringBoot(3)整合MyBatis 和MybatisPlus,image-20230809225319228,第13张

              2.6MyBatisPlus使用多表联查

              2.6.1在UserService中添加
                  List queryUserRole(Map map);
              
              2.6.2在UserServiceImpl中添加
                  @Autowired
                  private UserMapper userMapper;
                  @Override
                  public List queryUserRole(Map map) {
                      return userMapper.queryUserRole(map);
                  }
              
              2.6.3在UserMapper接口上添加
                   @Select("SELECT u.id,u.user_name,u.true_name,r.role_name FROM t_user u,t_role r WHERE u.roleId=r.id AND u.roleId='17'")
                   List queryUserRole(Map map) ;
              
              2.6.5在UserController中添加
                  // 连表查询
                  @GetMapping("/userRole")
                  public List userRole(String userName){
                      Map map = new HashMap();
                      map.put("user_name",userName);
                      List maps = userService.queryUserRole(map);
                      return maps;
                  }
              
              2.6.6两表联查成功

              SpringBoot(3)整合MyBatis 和MybatisPlus,image-20230809231237188,第14张