前提说明:
项目的springboot版本为:<version>3.3.2</version>
需要整合的mybatis-plus版本:<version>3.5.7</version>
废话不多说,开始造吧
1.准备好数据库和表
2.配置全局文件application.properties或者是application.yml(配置mapper的映射文件路径)
我这里是application.properties,配置如下:
#配置服务器端口号
server.port=9090
#连接数据库
spring.application.name=dormitory_backend
spring.datasource.url=jdbc:mysql://localhost:3306/dormitory?allowPublicKeyRetrieval=true&serverTimezone=Asia/Shanghai&useSSL=false
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#mybatis-plus配置mapper文件路径
mybatis-plus.mapper-locations=classpath:/mapper/*.xml
#打印sql日志
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
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的依赖:
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-annotation</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-core</artifactId>
<version>3.5.1</version>
</dependency>
至于为什么说是无效依赖,导入以上的依赖无法使用mybatis-plus自带的方法
发送请求时,后台产生以下报错:
Invalid bound statement (not found): com.dormitory.dormitory_backend.mapper.AttendanceMapper.deleteById
AttendanceMapper的deleteById方法是无效的绑定语句,也就是,无法识别到mybatis-plus自带的删除方法,但是可以识别自定义的mapper语句,能正常进行增删改查,也就是原mybatis的写法呗,但是,我想快速实现CRUD啊!于是,网上找了一个解决的方法,配置一个类,请看下文:
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.MybatisXMLLanguageDriver;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.mapping.DatabaseIdProvider;
import org.apache.ibatis.plugin.Interceptor;
import org.mybatis.spring.boot.autoconfigure.MybatisProperties;
import org.mybatis.spring.boot.autoconfigure.SpringBootVFS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.ResourceLoader;
import org.springframework.util.StringUtils;
import javax.sql.DataSource;
@Configuration
public class MybatisPlusConfig {
@Autowired
private DataSource dataSource;
@Autowired
private MybatisProperties properties;
@Autowired
private ResourceLoader resourceLoader = new DefaultResourceLoader();
@Autowired(required = false)
private Interceptor[] interceptors;
@Autowired(required = false)
private DatabaseIdProvider databaseIdProvider;
/**
* mybatis-plus分页插件
*/
@Bean
public PaginationInnerInterceptor paginationInnerInterceptor(){
PaginationInnerInterceptor page= new PaginationInnerInterceptor();
return page;
}
/**
* 这里全部使用mybatis-autoconfigure 已经自动加载的资源。不手动指定 <p> 配置文件和mybatis-boot的配置文件同步 @return
*/
@Bean
public MybatisSqlSessionFactoryBean mybatisSqlSessionFactoryBean() {
MybatisSqlSessionFactoryBean mybatisPlus = new MybatisSqlSessionFactoryBean();
mybatisPlus.setDataSource(dataSource);
mybatisPlus.setVfs(SpringBootVFS.class);
if (StringUtils.hasText(this.properties.getConfigLocation()))
mybatisPlus.setConfigLocation(this.resourceLoader.getResource(this.properties.getConfigLocation()));
if (!ObjectUtils.isEmpty(this.interceptors)) mybatisPlus.setPlugins(this.interceptors);
MybatisConfiguration mc = new MybatisConfiguration();
mc.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class);
// 数据库字段设计为驼峰命名,默认开启的驼峰转下划线会报错字段找不到
mc.setMapUnderscoreToCamelCase(true);
mybatisPlus.setConfiguration(mc);
if (this.databaseIdProvider != null) mybatisPlus.setDatabaseIdProvider(this.databaseIdProvider);
if (StringUtils.hasLength(this.properties.getTypeAliasesPackage()))
mybatisPlus.setTypeAliasesPackage(this.properties.getTypeAliasesPackage());
if (StringUtils.hasLength(this.properties.getTypeHandlersPackage()))
mybatisPlus.setTypeHandlersPackage(this.properties.getTypeHandlersPackage());
if (!ObjectUtils.isEmpty(this.properties.resolveMapperLocations()))
mybatisPlus.setMapperLocations(this.properties.resolveMapperLocations());
return mybatisPlus;
}
}
配置了这个类,确实是可以使用mybatis-plus自带的方法,但是自己写的方法却无法实现了
实现配置类后,请求自定义的新增方法:
实现配置类后,请求mybatis-plus自带的删除方法:
几经辗转,发现导入以下这个依赖可以实现同时使用自定义方法和mybatis-plus自带方法,注意:需要删除MybatisPlusConfig类,以及将原先导入的三个依赖替换成新的依赖就可以了
有效依赖---导入mybatis-plus的依赖:
---------------原依赖-----------------
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-annotation</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-core</artifactId>
<version>3.5.1</version>
</dependency>
--------------新依赖------------------
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-spring-boot3-starter</artifactId>
<version>3.5.7</version>
</dependency>
5.实现表对应的实体类
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("t_attendance")
public class Attendance {
@ApiModelProperty("自增id")
@TableId(value = "id",type = IdType.AUTO)
private Integer id;
@ApiModelProperty("账号(学号)")
@TableField("user_account")
private String userAccount;
@ApiModelProperty("缺勤原因")
@TableField("reason")
private String reason;
}
6.mapper和xml
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.dormitory.dormitory_backend.entity.Attendance;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface AttendanceMapper extends BaseMapper<Attendance> {
int insertAttendance(Attendance attendance);
int deleteAttendance(Integer id);
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.dormitory.dormitory_backend.mapper.AttendanceMapper">
<insert id="insertAttendance" parameterType="com.dormitory.dormitory_backend.entity.Attendance">
insert into t_attendance(user_account,reason) values(#{userAccount},#{reason})
</insert>
<delete id="deleteAttendance">
delete from t_attendance where id = #{id}
</delete>
</mapper>
7.service和impl
public interface AttendanceService {
int addAttendance(Attendance attendance);
int deleteAttendance(Integer id);
}
import com.dormitory.dormitory_backend.entity.Attendance;
import com.dormitory.dormitory_backend.mapper.AttendanceMapper;
import com.dormitory.dormitory_backend.service.AttendanceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class AttendanceServiceImpl implements AttendanceService {
@Autowired
private AttendanceMapper attendanceMapper;
/**
* 自定义的新增方法
* @param attendance
* @return
*/
@Override
public int addAttendance(Attendance attendance) {
int insert = attendanceMapper.insertAttendance(attendance);
return insert;
}
/**
* plus自带的删除方法
* @param id
* @return
*/
@Override
public int deleteAttendance(Integer id) {
return attendanceMapper.deleteById(id);
}
}
8.controller
import com.dormitory.dormitory_backend.entity.Attendance;
import com.dormitory.dormitory_backend.service.AttendanceService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/attendance")
@Api(tags = {"考勤管理"})
public class AttendanceController {
@Autowired
private AttendanceService attendanceService;
@PostMapping("/addAttendance")
public int addAttendance(@RequestBody Attendance attendance){
int addAttendance = attendanceService.addAttendance(attendance);
return addAttendance;
}
@DeleteMapping("/deleteAttendance")
public int deleteAttendance(Integer id){
int addAttendance = attendanceService.deleteAttendance(id);
return addAttendance;
}
}
9.实现
唠一唠:出现Invalid bound statement (not found)问题的原因可能有哪些
1.全局配置文件没配好?
检查全局配置文件application.properties或application.yml是否配置扫描mapper包的文件路径
#mybatis配置mapper文件路径
#mybatis.mapper-locations=classpath:/mapper/*.xml
#mybatis-plus配置mapper文件路径
mybatis-plus.mapper-locations=classpath:/mapper/*.xml
2.启动类没加包扫描注解 ?
检查启动类上是否添加包扫描注解
@SpringBootApplication
@MapperScan("项目路径.mapper")
public class DormitoryBackendApplication {
public static void main(String[] args) {
SpringApplication.run(DormitoryBackendApplication.class, args);
}
3.没使用@Mapper注解?
XXXmapper.java类是否使用@Mapper注解
@Mapper
public interface AttendanceMapper extends BaseMapper<Attendance> {}
4.命名空间不正确?
检查XXXmapper.xml的命名空间是否正确,是否能跳转到对应的XXXmapper.java
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.dormitory.dormitory_backend.mapper.AttendanceMapper"></mapper>
正常能跳转会有箭头图标,点击能跳转(下载一个插件)