当前位置:   article > 正文

Spring Boot3.3.X整合Mybatis-Plus_springboot 3.3.2 mybatis-plus-boot-starter

springboot 3.3.2 mybatis-plus-boot-starter

前提说明:

项目的springboot版本为:<version>3.3.2</version>

需要整合的mybatis-plus版本:<version>3.5.7</version>

废话不多说,开始造吧

1.准备好数据库和表

2.配置全局文件application.properties或者是application.yml(配置mapper的映射文件路径)

我这里是application.properties,配置如下:

  1. #配置服务器端口号
  2. server.port=9090
  3. #连接数据库
  4. spring.application.name=dormitory_backend
  5. spring.datasource.url=jdbc:mysql://localhost:3306/dormitory?allowPublicKeyRetrieval=true&serverTimezone=Asia/Shanghai&useSSL=false
  6. spring.datasource.username=root
  7. spring.datasource.password=root
  8. spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
  9. #mybatis-plus配置mapper文件路径
  10. mybatis-plus.mapper-locations=classpath:/mapper/*.xml
  11. #打印sql日志
  12. mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
  13. logging.level.com.dormitory.dormitory_backend.mapper=DEBUG

3.启动类配置包扫描注解和路径信息

配置之前先看下我这边的包结构

启动类,造吧?找到有@SpringBootApplication注解的类就是了,在其位置加上包扫描注解@MapperScan("com.dormitory.dormitory_backend.mapper")

注意括号里面的内容需要根据自己的包结构来配置,com.dormitory.dormitory_backend是我的包结构,主要看java,实在不懂,那就任意打开一个XXXmapper.java文件,看其包结构,框起来的一整个复制粘贴上去就可以了


4.导入依赖:

无效依赖---我尝试过导入网上的各种mybatis-plus的依赖:

  1. <dependency>
  2. <groupId>com.baomidou</groupId>
  3. <artifactId>mybatis-plus-boot-starter</artifactId>
  4. <version>3.5.1</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>com.baomidou</groupId>
  8. <artifactId>mybatis-plus-annotation</artifactId>
  9. <version>3.5.1</version>
  10. </dependency>
  11. <dependency>
  12. <groupId>com.baomidou</groupId>
  13. <artifactId>mybatis-plus-core</artifactId>
  14. <version>3.5.1</version>
  15. </dependency>

至于为什么说是无效依赖,导入以上的依赖无法使用mybatis-plus自带的方法

发送请求时,后台产生以下报错:

Invalid bound statement (not found): com.dormitory.dormitory_backend.mapper.AttendanceMapper.deleteById

AttendanceMapper的deleteById方法是无效的绑定语句,也就是,无法识别到mybatis-plus自带的删除方法,但是可以识别自定义的mapper语句,能正常进行增删改查,也就是原mybatis的写法呗,但是,我想快速实现CRUD啊!于是,网上找了一个解决的方法,配置一个类,请看下文:

  1. import com.baomidou.mybatisplus.core.MybatisConfiguration;
  2. import com.baomidou.mybatisplus.core.MybatisXMLLanguageDriver;
  3. import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
  4. import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
  5. import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
  6. import org.apache.ibatis.mapping.DatabaseIdProvider;
  7. import org.apache.ibatis.plugin.Interceptor;
  8. import org.mybatis.spring.boot.autoconfigure.MybatisProperties;
  9. import org.mybatis.spring.boot.autoconfigure.SpringBootVFS;
  10. import org.springframework.beans.factory.annotation.Autowired;
  11. import org.springframework.context.annotation.Bean;
  12. import org.springframework.context.annotation.Configuration;
  13. import org.springframework.core.io.DefaultResourceLoader;
  14. import org.springframework.core.io.ResourceLoader;
  15. import org.springframework.util.StringUtils;
  16. import javax.sql.DataSource;
  17. @Configuration
  18. public class MybatisPlusConfig {
  19. @Autowired
  20. private DataSource dataSource;
  21. @Autowired
  22. private MybatisProperties properties;
  23. @Autowired
  24. private ResourceLoader resourceLoader = new DefaultResourceLoader();
  25. @Autowired(required = false)
  26. private Interceptor[] interceptors;
  27. @Autowired(required = false)
  28. private DatabaseIdProvider databaseIdProvider;
  29. /**
  30. * mybatis-plus分页插件
  31. */
  32. @Bean
  33. public PaginationInnerInterceptor paginationInnerInterceptor(){
  34. PaginationInnerInterceptor page= new PaginationInnerInterceptor();
  35. return page;
  36. }
  37. /**
  38. * 这里全部使用mybatis-autoconfigure 已经自动加载的资源。不手动指定 <p> 配置文件和mybatis-boot的配置文件同步 @return
  39. */
  40. @Bean
  41. public MybatisSqlSessionFactoryBean mybatisSqlSessionFactoryBean() {
  42. MybatisSqlSessionFactoryBean mybatisPlus = new MybatisSqlSessionFactoryBean();
  43. mybatisPlus.setDataSource(dataSource);
  44. mybatisPlus.setVfs(SpringBootVFS.class);
  45. if (StringUtils.hasText(this.properties.getConfigLocation()))
  46. mybatisPlus.setConfigLocation(this.resourceLoader.getResource(this.properties.getConfigLocation()));
  47. if (!ObjectUtils.isEmpty(this.interceptors)) mybatisPlus.setPlugins(this.interceptors);
  48. MybatisConfiguration mc = new MybatisConfiguration();
  49. mc.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class);
  50. // 数据库字段设计为驼峰命名,默认开启的驼峰转下划线会报错字段找不到
  51. mc.setMapUnderscoreToCamelCase(true);
  52. mybatisPlus.setConfiguration(mc);
  53. if (this.databaseIdProvider != null) mybatisPlus.setDatabaseIdProvider(this.databaseIdProvider);
  54. if (StringUtils.hasLength(this.properties.getTypeAliasesPackage()))
  55. mybatisPlus.setTypeAliasesPackage(this.properties.getTypeAliasesPackage());
  56. if (StringUtils.hasLength(this.properties.getTypeHandlersPackage()))
  57. mybatisPlus.setTypeHandlersPackage(this.properties.getTypeHandlersPackage());
  58. if (!ObjectUtils.isEmpty(this.properties.resolveMapperLocations()))
  59. mybatisPlus.setMapperLocations(this.properties.resolveMapperLocations());
  60. return mybatisPlus;
  61. }
  62. }

配置了这个类,确实是可以使用mybatis-plus自带的方法,但是自己写的方法却无法实现了

实现配置类后,请求自定义的新增方法:

实现配置类后,请求mybatis-plus自带的删除方法:

几经辗转,发现导入以下这个依赖可以实现同时使用自定义方法和mybatis-plus自带方法,注意:需要删除MybatisPlusConfig类,以及将原先导入的三个依赖替换成新的依赖就可以了

有效依赖---导入mybatis-plus的依赖:

  1. ---------------原依赖-----------------
  2. <dependency>
  3. <groupId>com.baomidou</groupId>
  4. <artifactId>mybatis-plus-boot-starter</artifactId>
  5. <version>3.5.1</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>com.baomidou</groupId>
  9. <artifactId>mybatis-plus-annotation</artifactId>
  10. <version>3.5.1</version>
  11. </dependency>
  12. <dependency>
  13. <groupId>com.baomidou</groupId>
  14. <artifactId>mybatis-plus-core</artifactId>
  15. <version>3.5.1</version>
  16. </dependency>
  17. --------------新依赖------------------
  18. <dependency>
  19. <groupId>com.baomidou</groupId>
  20. <artifactId>mybatis-plus-spring-boot3-starter</artifactId>
  21. <version>3.5.7</version>
  22. </dependency>

5.实现表对应的实体类

  1. import com.baomidou.mybatisplus.annotation.IdType;
  2. import com.baomidou.mybatisplus.annotation.TableField;
  3. import com.baomidou.mybatisplus.annotation.TableId;
  4. import com.baomidou.mybatisplus.annotation.TableName;
  5. import io.swagger.annotations.ApiModelProperty;
  6. import lombok.AllArgsConstructor;
  7. import lombok.Data;
  8. import lombok.NoArgsConstructor;
  9. @Data
  10. @AllArgsConstructor
  11. @NoArgsConstructor
  12. @TableName("t_attendance")
  13. public class Attendance {
  14. @ApiModelProperty("自增id")
  15. @TableId(value = "id",type = IdType.AUTO)
  16. private Integer id;
  17. @ApiModelProperty("账号(学号)")
  18. @TableField("user_account")
  19. private String userAccount;
  20. @ApiModelProperty("缺勤原因")
  21. @TableField("reason")
  22. private String reason;
  23. }

6.mapper和xml

  1. import com.baomidou.mybatisplus.core.mapper.BaseMapper;
  2. import com.dormitory.dormitory_backend.entity.Attendance;
  3. import org.apache.ibatis.annotations.Mapper;
  4. @Mapper
  5. public interface AttendanceMapper extends BaseMapper<Attendance> {
  6. int insertAttendance(Attendance attendance);
  7. int deleteAttendance(Integer id);
  8. }
  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4. "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <mapper namespace="com.dormitory.dormitory_backend.mapper.AttendanceMapper">
  6. <insert id="insertAttendance" parameterType="com.dormitory.dormitory_backend.entity.Attendance">
  7. insert into t_attendance(user_account,reason) values(#{userAccount},#{reason})
  8. </insert>
  9. <delete id="deleteAttendance">
  10. delete from t_attendance where id = #{id}
  11. </delete>
  12. </mapper>

7.service和impl

  1. public interface AttendanceService {
  2. int addAttendance(Attendance attendance);
  3. int deleteAttendance(Integer id);
  4. }
  1. import com.dormitory.dormitory_backend.entity.Attendance;
  2. import com.dormitory.dormitory_backend.mapper.AttendanceMapper;
  3. import com.dormitory.dormitory_backend.service.AttendanceService;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.stereotype.Service;
  6. @Service
  7. public class AttendanceServiceImpl implements AttendanceService {
  8. @Autowired
  9. private AttendanceMapper attendanceMapper;
  10. /**
  11. * 自定义的新增方法
  12. * @param attendance
  13. * @return
  14. */
  15. @Override
  16. public int addAttendance(Attendance attendance) {
  17. int insert = attendanceMapper.insertAttendance(attendance);
  18. return insert;
  19. }
  20. /**
  21. * plus自带的删除方法
  22. * @param id
  23. * @return
  24. */
  25. @Override
  26. public int deleteAttendance(Integer id) {
  27. return attendanceMapper.deleteById(id);
  28. }
  29. }

8.controller

  1. import com.dormitory.dormitory_backend.entity.Attendance;
  2. import com.dormitory.dormitory_backend.service.AttendanceService;
  3. import io.swagger.annotations.Api;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.web.bind.annotation.*;
  6. @RestController
  7. @RequestMapping("/attendance")
  8. @Api(tags = {"考勤管理"})
  9. public class AttendanceController {
  10. @Autowired
  11. private AttendanceService attendanceService;
  12. @PostMapping("/addAttendance")
  13. public int addAttendance(@RequestBody Attendance attendance){
  14. int addAttendance = attendanceService.addAttendance(attendance);
  15. return addAttendance;
  16. }
  17. @DeleteMapping("/deleteAttendance")
  18. public int deleteAttendance(Integer id){
  19. int addAttendance = attendanceService.deleteAttendance(id);
  20. return addAttendance;
  21. }
  22. }

9.实现

唠一唠:出现Invalid bound statement (not found)问题的原因可能有哪些

1.全局配置文件没配好?

检查全局配置文件application.properties或application.yml是否配置扫描mapper包的文件路径

  1. #mybatis配置mapper文件路径
  2. #mybatis.mapper-locations=classpath:/mapper/*.xml
  3. #mybatis-plus配置mapper文件路径
  4. mybatis-plus.mapper-locations=classpath:/mapper/*.xml

2.启动类没加包扫描注解 ?

检查启动类上是否添加包扫描注解 

  1. @SpringBootApplication
  2. @MapperScan("项目路径.mapper")
  3. public class DormitoryBackendApplication {
  4. public static void main(String[] args) {
  5. SpringApplication.run(DormitoryBackendApplication.class, args);
  6. }

3.没使用@Mapper注解?

XXXmapper.java类是否使用@Mapper注解

  1. @Mapper
  2. public interface AttendanceMapper extends BaseMapper<Attendance> {}

4.命名空间不正确?

检查XXXmapper.xml的命名空间是否正确,是否能跳转到对应的XXXmapper.java

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4. "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <mapper namespace="com.dormitory.dormitory_backend.mapper.AttendanceMapper"></mapper>

正常能跳转会有箭头图标,点击能跳转(下载一个插件)

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

闽ICP备14008679号