在SQL server中没有limit方法,实现分页查询就比较麻烦,除此之外,除了要获取分页信息,还要获取数据总量,所以要进行两次查询。刚开始我想着使用一个查询,同时获取分页信息及数据总量,主要就是将数据总量作为一个列,附加在查询结果的后面返回,比如下面的代码,主要使用了 row_number() over 和 COUNT (*) OVER () AS total 两个方法,然后再将数据一一对应
1 2 3 4
@Query(value="SELECT * FROM (select row_number() over (order by RecordTime ) as ROW_COUNT , *,COUNT (*) OVER () AS total from " + "secHis t where sectionId =?1 and (RecordTime between ?2 and ?3)) as b " + "where ROW_COUNT between (?4-1)*?4 and ?4*?5",nativeQuery=true) List<Object> findBySectionIdAndRecordTimeBetweenMax(Integer section, Date starttime, Date endtime,Integer pageIndex,Integer pageSize);
// 定义分页查询 @Query( value = "SELECT * FROM Users ORDER BY id", countQuery = "SELECT count(*) FROM Users", nativeQuery = true) Page<User> findAllUsersWithPagination(Pageable pageable);
@Query(value = "select row_number() over (order by RecordTime ) as id, * from secHis t" + " where sectionId =:section and (RecordTime between :starttime and :endtime) order by RecordTime", countQuery = "SELECT count(*) FROM SecHis where sectionId =:section and (RecordTime between :starttime and :endtime)", nativeQuery = true) Page<SecHis> findBySectionIdAndRecordTimeBetweenPage(Integer section, Date starttime, Date endtime, Pageable pageable);
(2) Could not locate ordinal parameter [1], expecting one of 解决了分页查询的方言问题之后,出现了无法定位参数的问题,显示这三个参数都没有找到。
最后将位置参数,改为了命名参数
1 2 3 4 5 6 7 8 9
// 正确的查询语句 @Query(value = "select row_number() over (order by RecordTime ) as id, * from secHis t" + " where sectionId =:section and (RecordTime between :starttime and :endtime) order by RecordTime",countQuery = "SELECT count(*) FROM SecHis",nativeQuery = true) Page<SecHis> findBySectionIdAndRecordTimeBetweenPage(Integer section, Date starttime, Date endtime, Pageable pageable);
// 错误的查询语句 @Query(value = "select row_number() over (order by RecordTime ) as id, * from secHis t" + " where sectionId =?1 and (RecordTime between ?2 and ?3) order by RecordTime",countQuery = "SELECT count(*) FROM SecHis",nativeQuery = true) Page<SecHis> findBySectionIdAndRecordTimeBetweenPage(Integer section, Date starttime, Date endtime, Pageable pageable);