SpringBoot集成mybatis-plus
一、导入依赖
<!-- jdbc驱动 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!--Mybatis Plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.0</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
二、配置application.properties
#mysql
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=123456
#扫描mybatis-plus 扫描xml文件。(我放在resource下的mapper文件中)
mybatis-plus.mapper-locations=classpath*:mapper/*.xml
三、创建分页组件的config
官网粘贴过来的,直接拿去用,不用改
@Configuration
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}
四、准备实体类、Mapper、xml
实体类Student
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class Student implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.AUTO)
private Long id;
private String name;
private Integer age;
public Student(String name, Integer age) {
this.name = name;
this.age = age;
}
public Student() {
}
}
StudentMapper
@Mapper
public interface StudentMapper extends BaseMapper<Student> {
}
StudentMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.demo.mapper.StudentMapper">
</mapper>
五、单元测试
主要就两步:
1.创建分页对象Page,最后查出来的数据都会回传到这个Page对象中。【传入的泛型,必须有无惨构造方法,否则第二步会报错】
第一个参数是第几页,从1开始;
第二个参数:每页显示几条数据。
IPage<Student> pages = new Page<>(0, 5);
2.分页查询。
第一个参数是分页对象Page;
第二个参数是查询条件,可以自定义查询条件
studentMapper.selectPage(pages, null);
@SpringBootTest
class DemoApplicationTests {
@Autowired
StudentMapper studentMapper;
@Test
void contextLoads() {
//添加数据到数据库
for (int i = 0; i < 20; i++) {
Student student = new Student("p" + i, 18);
studentMapper.insert(student);
}
//循环打印查出来的数据
IPage<Student> pages;
int current = 1;
do {
pages = new Page<>(current++, 5);
studentMapper.selectPage(pages, null);
List<Student> studentList = pages.getRecords();
for (Student student : studentList) {
System.out.println(student);
}
System.out.println("-------------------");
} while (pages != null && pages.getPages() != pages.getCurrent());
}
}
踩坑:
原本我使用studentMapper.selectPage(studentPage,null)查询分页的时候,报如下错误:
原因是因为我要查询的Student对象,我重写了构造方法,没有了默认的无惨构造方法,所以报错。解决方法:在实体类中加上无惨构造方法。