我可以将 JPQL 的结果限制为 return 个结果吗?
Can I limit the result of JPQL to just return one result?
我想在存储库界面中做这样的事情(在 Spring Data JPA 中):
interface myRepository extends JpaRepository<A, Long> {
@Query("select a from A a where a.x = :x")
A findFirstBySomeCondition(int x);
}
但我只需要第一个结果。 (已编辑:实际查询条件非常复杂,所以我更愿意使用 @Query 而不是 findFirst 或 findTop ...)
我不想使用标准 api,因为它很冗长。
我不想使用本机查询,因为我必须手动编写查询字符串。
那么,鉴于上述限制性要求,还有解决方案吗?
谢谢!
您可以为此使用 Pageable
。该文档显示了不同的使用方式:http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.limit-query-result
查询方式的结果可以通过关键字first或top来限定,两者可以交替使用。可以将可选数值附加到 top/first 以指定要返回的最大结果大小。
interface myRepository extends JpaRepository<A, Long> {
@Query("select a from A a where a.x = :x")
Page<A> findFirstBySomeCondition(@Param("x") int x,Pageable pageable);
}
实施Class:
Page<A> results = repository.findFirstBySomeCondition(x,new PageRequest(0, 1));
A object = results.getContent.get(0);
我想在存储库界面中做这样的事情(在 Spring Data JPA 中):
interface myRepository extends JpaRepository<A, Long> {
@Query("select a from A a where a.x = :x")
A findFirstBySomeCondition(int x);
}
但我只需要第一个结果。 (已编辑:实际查询条件非常复杂,所以我更愿意使用 @Query 而不是 findFirst 或 findTop ...)
我不想使用标准 api,因为它很冗长。
我不想使用本机查询,因为我必须手动编写查询字符串。
那么,鉴于上述限制性要求,还有解决方案吗?
谢谢!
您可以为此使用 Pageable
。该文档显示了不同的使用方式:http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.limit-query-result
查询方式的结果可以通过关键字first或top来限定,两者可以交替使用。可以将可选数值附加到 top/first 以指定要返回的最大结果大小。
interface myRepository extends JpaRepository<A, Long> {
@Query("select a from A a where a.x = :x")
Page<A> findFirstBySomeCondition(@Param("x") int x,Pageable pageable);
}
实施Class:
Page<A> results = repository.findFirstBySomeCondition(x,new PageRequest(0, 1));
A object = results.getContent.get(0);