如何在JPA查询中查询前10个结果?

dsf9zpds  于 2023-06-23  发布在  其他
关注(0)|答案(2)|浏览(416)

我在Java项目中使用JPA。我的大多数函数都是使用@Query注解在JpaRepository接口中声明的。例如,我有一个这样定义的:

  1. List<Notification> findDelivered(@Param("patientId") long patientId);

我想对这个设置一个限制,以便只得到前10名的结果。我尝试在查询的末尾添加“LIMIT 10”,但这不起作用。
我可以找到许多例子,其中PageRequest的示例作为第二个参数传递给findDelivered。我试过了,但这是一个语法错误:函数需要一个整数作为第二个参数(我不知道为什么)。

j7dteeu8

j7dteeu81#

尝试使用JPA获得前10个结果:使用***@Param(“patientId”)作为NamedParameters**

  1. List <notification> = notif.createQuery("select * from notification where patientId = :patientId order by patient_id")
  2. .setFirstResult(0)
  3. .setMaxResults(10)
  4. .getResultList();

或者使用***可分页***:

  1. Page<notification> findAll(Pageable pageable);
  2. ...
  3. Page<notification> notification = NotificationRepository.findAll(PageRequest.of(0, 10));

别忘了你的命令

gc0ot86w

gc0ot86w2#

https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.limit-query-result

  1. Page<Notification> queryFirst10ByPatientId(long patientId, Pageable pageable);
  2. Slice<Notification> findTop10ByPatientId(long patientId, Pageable pageable);
  3. List<Notification> findFirst10ByPatientId(long patientId, Sort sort);
  4. List<Notification> findTop10ByPatientId(long patientId, Pageable pageable);

相关问题