我可以限制JPQL的结果只返回一个结果吗?

xin*_*ing 1 spring jpa jpql spring-data spring-data-jpa

我想在存储库接口中执行类似的操作(在Spring Data JPA中):

interface myRepository extends JpaRepository<A, Long> {
    @Query("select a from A a where a.x = :x")
    A findFirstBySomeCondition(int x);
}
Run Code Online (Sandbox Code Playgroud)

但我只需要第一个结果.(编辑:实际查询条件非常复杂,所以我更喜欢使用@Query代替findFirst或findTop ...)

我不想使用标准api,因为它很冗长.

我不想使用本机查询,因为我将不得不手动编写查询字符串.

那么,考虑到上面的限制要求,是否还有解决方案?

谢谢!

ozg*_*gur 5

查询方法的结果可以通过关键字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);
}
Run Code Online (Sandbox Code Playgroud)

实施班级:

Page<A> results = repository.findFirstBySomeCondition(x,new   PageRequest(0, 1));
A object = results.getContent.get(0);
Run Code Online (Sandbox Code Playgroud)