Mybatis 提供了一个分页插件PageHelper,它会帮助我们自动完成分页和获取总数量的操作,可以方便实现分页查询。
第一步,在pom.xml文件引入PageHelper依赖。
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
</dependency>
第二步, 编写Controller层代码(例子如下):
@GetMapping("/page")
public Result<PageResult> page(EmployeePageQueryDTO employeePageQueryDTO){
//将数据打印输出在控制台上
log.info("员工分页查询,参数为: {}", employeePageQueryDTO);
PageResult pageResult = employeeService.page(employeePageQueryDTO);
return Result.success(pageResult);
}
第三步,编写Service层代码(例子如下):
public PageResult page(EmployeePageQueryDTO employeePageQueryDTO) {
//select * from employee limit 1, 10
//开始分页查询
//startPage方法的两个参数分别为页数,每页总记录数
PageHelper.startPage(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());
Page<Employee> page = employeeMapper.pageQuery(employeePageQueryDTO);
long total = page.getTotal();
List<Employee> records = page.getResult();
return new PageResult(total, records);
}
第四步,为Mapper层编写xml映射文件,不推荐使用注解编写Sql语句(比较复杂的sql语句比较编写在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.sky.mapper.EmployeeMapper">
<select id="pageQuery" resultType="com.sky.entity.Employee">
select * from employee
<where>
<if test="name != null and name != ''">
and name like concat('%', #{name}, '%')
</if>
</where>
order by create_time desc
</select>
</mapper>
如此,便可成功实现分页查询功能。
标签:employeePageQueryDTO,分页,插件,PageHelper,Mybatis,编写,查询,page From: https://blog.csdn.net/2301_76809936/article/details/141390797