016 Mybatis集成分页插件pageHelper

<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <version>1.2.10</version>
</dependency>

PageHelper是中国人编写的,里面的注释全部都是中文,很便于阅读。先来编写配置application.properties文件

###配置PageHelper
pagehelper.helper-dialect=mysql	###这里注意要换成你的数据库类型
pagehelper.reasonable=true
pagehelper.support-methods-arguments=true
pagehelper.params=count=countSql
pagehelper.page-size-zero=true

用Student为例,在StudentMapper里编写一个查询全部的方法

/**
 * Student类的mapper接口
 */
public interface StudentMapper {
    /**
     * 查询全部学生
     */
    @Select("SELECT * FROM student")
    public List<Student> getStudentList();
}

在StudentService里调用pageHelper来分页,虽然调用的是查询全部的接口,但是pageHelper修改了sql语句,将查询全部根据pageNum和pageSize来分页查询,这里通过一个输出语句来验证是否真的修改了sql语句,由查询全部改为分页查询。返回类型PageInfo是pageHelper的工具类,支持泛型。

/**
 * Student类的业务逻辑类
 */
@Service
public class StudentService {
    @Autowired
    private StudentMapper studentMapper;//在启动入口类用@MapperScan注解扫描mapper接口,idea可能会在这里报错,不用担心只是误报

    /**
     * 分页查询学生
     * @param pageNun  当前页面
     * @param pageSize  页面容量
     * @return
     */
    public PageInfo<Student> getStudentPage(int pageNun,int pageSize){
        PageHelper.startPage(pageNun, pageSize);
        List<Student> studentList = studentMapper.getStudentList();
        System.out.println("测试一下是查询的全部,是否真的分页查询了:"+JSONArray.toJSONString(studentList));
        PageInfo<Student> studentPageInfo = new PageInfo<>(studentList);
        return studentPageInfo;
    }
}
@RestController
public class Test {
    @Autowired
    private StudentService studentService;

    /**
     * 分页测试
     *
     * @param pageNum  当前页
     * @param pageSize 页面容量
     * @return
     */
    @GetMapping(value = "/page")
    public String page(int pageNum, int pageSize) {
        PageInfo<Student> studentPageInfo = studentService.getStudentPage(pageNum, pageSize);
        System.out.println("总页数:" + studentPageInfo.getPages());
        System.out.println("当前页:" + studentPageInfo.getPageNum());
        System.out.println("上一页:" + studentPageInfo.getPrePage());
        System.out.println("下一页:" + studentPageInfo.getNextPage());
        System.out.println("总共有多少页:" + JSONArray.toJSONString(studentPageInfo.getNavigatePages()));
        System.out.println("所有导航页号:" + JSONArray.toJSONString(studentPageInfo.getNavigatepageNums()));
        System.out.println("当前页内容:" + studentPageInfo.getList());
        //一般来说直接将studentPageInfo对象json化传输给前端,因为还需要页码信息
        return JSONArray.toJSONString(studentPageInfo);
    }
}

调用一下分页接口,当前页面1,页面容量为2

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值