使用Spring Data JPA和@Query注释仅获取第一个/最后一个元素 [英] Fetching only first/last element using Spring Data JPA and @Query annotation
问题描述
编辑:关于此问题的第二和第四个答案中提供了此问题的解决方案用于Spring-Data-JPA注释的setMaxResults?
Solutions to this problem are provided in the second and fourth answer regarding this question setMaxResults for Spring-Data-JPA annotation?
目标:获取最大/最小元素by property z使用Spring Data JPA存储库和Spring Query注释。
Goal: Fetch the largest/smallest element by property z using a Spring Data JPA repository and the Spring Query annotation.
到目前为止我有什么
@Query("SELECT xelement FROM x xelement ORDER BY xelement.z")
public List<X> findFirstElement();
问题:此查询获取所有元素(这不是真正有效) 。如果我直接使用EntityManager,我可以使用
Problem: This query fetches all elements (which is not really effective). If I would use the EntityManager direcly, I could set the number of results using
entityManager.setMaxResults(1)
只能获得第一个元素。
问题:如何使用 @Query 注释指定最大结果数?
Question: How do I specify the maximum number of results using the @Query annotation?
创意:正在使用大小为0的PageRequest吗?
Idea: Is using a PageRequest of size 0 the way to go?
约束:我知道FindFirstBy ......查询功能但我想/必须使用 @Query
注释。
Constraints: I am aware of the "FindFirstBy...." query feature but I want/have to use the @Query
annotation.
推荐答案
只需将nativeQuery添加到@Query注释即可使用sql的limit属性。但是,还有另一种更好的方法。存储库方法中的可分页类将在不触及@Query注释的情况下解决您的问题:
You can use the limit property of sql just by adding nativeQuery to @Query annotation. However, there is another and a better way of doing this. Pageable class in your repository method will solve your problem without touching your @Query annotation:
@Query(value = "SELECT xelement FROM x xelement ORDER BY xelement.z")
List<X> findFirstElement(Pageable limit);
要设置限制和偏移量,请使用以下方法调用此存储库方法:
To set the limit and offset, use should call this repository method as follows:
List<X> xValues = xRepository.findFirstElement(new PageRequest(0, 1));
这里1对应你想要的限额。
Here 1 corresponds to the limit which you want.
这篇关于使用Spring Data JPA和@Query注释仅获取第一个/最后一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!