springboot分页功能

2023-04-24 17:49:55 浏览数 (1)

第一步:导入依赖

代码语言:javascript复制
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <version>${pagehelper}</version>
</dependency>

第二步添加配置:

代码语言:javascript复制
spring:
main:
 allow-circular-references: true

第三开始写代码

PageResult类
代码语言:javascript复制
package com.huike.review.util;
​
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
​
import java.io.Serializable;
import java.util.List;
​
/**
 * 封装分页查询结果
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class PageResult implements Serializable {
​
    private long total; //总记录数
​
    private List records; //当前页数据集合
​
}
mapper层:
代码语言:javascript复制
​
mapper文件
    
Page<Employee> page(String name);
​
xml文件
//写的sql语句,注意别写分号了
    <select id="page" resultType="employee">
        select * from employee
        <where>
            <if test="name!=null and name!=''">
                name like concat('%',#{name},'%')
            </if>
        </where>
        order by create_time desc
    </select>
service层
代码语言:javascript复制
参数:
PageResult page(String name,Integer page,Integer pagesize);
代码语言:javascript复制
public PageResult page(String name,Integer page,Integer pagesize) {
    //第一步:设置分页条件
    PageHelper.startPage(page,pagesize);
    //第二步:调用mapper对象进行方法
    Page<Employee> pageInfo= employeeMapper.page(name);
    //然后把总结果集封装到page中
    long total = pageInfo.getTotal();
    //Employee要查询的实体类对象
    List<Employee> result = pageInfo.getResult();
    //然后把数据封装到类中
    PageResult pageResult = new PageResult(total,result);
    return pageResult;
}
controller层
代码语言:javascript复制
@ApiOperation("员工条件分页")
@GetMapping("/page")
@ApiImplicitParams({
        @ApiImplicitParam(name = "name",value = "员工姓名",required = false),
        @ApiImplicitParam(name = "page",value = "页码",required = true),
        @ApiImplicitParam(name = "pageSize",value = "每页的数据",required = true),
})
public Result<PageResult> page(@RequestParam(required = false) String name,
                               @RequestParam Integer page,
                               @RequestParam Integer pageSize){
    PageResult page1 = employeeService.page(name,page, pageSize);
    return Result.success(page1);
}

0 人点赞