由于在项目中要求使用Pageable实现分页查询,就简单学习了一下。
在此记录一下操作案例。
Pageable pageable = new PageRequest(page, size, Sort.Direction.DESC, "key");
下面简单介绍一下上面的这一行代码:
Pageable 必须引用spring的包。否则后面是不能new PageRequest的!!!!
page即当前页。
size代表每页有几条记录。
第三个参数是排序字段, Sort.Direction.DESC是倒序的意思。
最后一个参数是排序关键字,将按照这个关键字进行排序。
介绍完这个方法本身,下面介绍数据库操作。使用Pageable 时不能使用原生sql。官网说能,我也百度了许多的例子,都运行不起来。下面讲我的办法:
@Query(" from LoginTable k where k.loginName = ?1")
public Page<LoginTable> getLoginInfo(String loginName, Pageable pageable);
不用在@Query中使用
value=
和nativeQuery = true
形参里面加一个Pageable pageable
使用实体类的类型:LoginTable
,而不是数据库类型:login_table
接收参数使用Page<>
,而不是List<>
表名起别名
,通过别名去调用。(我遇到的问题,不起别名调不到)
数据库操作介绍完了,下面介绍一下调用:
Page<LoginTable> pageList = loginRepository.getLoginInfo(loginName,pageable);
依旧使用Page接收
形参加pageable(此时的pageable应该是已经定义好的,有当前页,页容量,排序字段等属性)