admin

Java Spring JPA分页如果超过一页,则无法正常工作

sql

我正在尝试将jpa分页与自定义查询一起使用。

如果与2种情况相匹配,则分页有效。

情况1 :

  • 如果可用数据少于10个且请求的页码为0

如果没有,请求不起作用

情况2:

  • 如果可用数据大于10,且请求的页码为1

如果没有分页是行不通的。

我不知道问题所在。有帮助吗?

提前致谢。

@Repository
public interface SmsLogRepository extends JpaRepository<SmsLog, Long> {

@Query(value = "select * from sms_log s where s.phone_number = (:ph) \n#pageable\n", nativeQuery = true)
Page<SmsLog> findByPhoneNumber(@Param("ph") String phoneNumber, Pageable pageable);

@Query(value = "select * from sms_log s where s.phone_number = (:ph) AND s.message_timestamp between (:fromdate) and (:todate) \n#pageable\n", nativeQuery = true)
Page<SmsLog> findByPhoneNumberAndDate(@Param("ph") String phoneNumber, @Param("fromdate") String fromDate, @Param("todate") String todate, Pageable pageable);

@Query(value = "select * from sms_log s where s.message_timestamp between (:fromdate) and (:todate) \n#pageable\n", nativeQuery = true)
Page<SmsLog> findByDate(@Param("fromdate") String fromDate, @Param("todate") String todate, Pageable pageable);
}

要求 :

PageRequest pageRequest = new PageRequest(page, 10, new Sort(new Sort.Order(Sort.Direction.DESC, "message_timestamp")));
            return logRepository.findByPhoneNumber(ph, pageRequest);

阅读 207

收藏
2021-07-01

共1个答案

admin

花了一段时间后,我找到了答案

我错过了计数查询。添加计数查询分页后,就像魅力:)

@Repository
public interface SmsLogRepository extends JpaRepository<SmsLog, Long> {

@Query(value = "select * from sms_log s where s.phone_number = (:ph) \n#pageable\n", countQuery = "select count(*) from sms_log s where s.phone_number = (:ph) \n#pageable\n", nativeQuery = true)
Page<SmsLog> findByPhoneNumber(@Param("ph") String phoneNumber, Pageable pageable);

@Query(value = "select * from sms_log s where s.phone_number = (:ph) AND s.message_timestamp between (:fromdate) and (:todate) \n#pageable\n",countQuery = "select count(*) from sms_log s where s.phone_number = (:ph) AND s.message_timestamp between (:fromdate) and (:todate) \n#pageable\n", nativeQuery = true)
Page<SmsLog> findByPhoneNumberAndDate(@Param("ph") String phoneNumber, @Param("fromdate") String fromDate, @Param("todate") String todate, Pageable pageable);

@Query(value = "select * from sms_log s where s.message_timestamp between (:fromdate) and (:todate) \n#pageable\n",countQuery = "select count(*) from sms_log s where s.message_timestamp between (:fromdate) and (:todate) \n#pageable\n", nativeQuery = true)
Page<SmsLog> findByDate(@Param("fromdate") String fromDate, @Param("todate") String todate, Pageable pageable);
}
2021-07-01