简体   繁体   English

使用Spring Data JPA和@Query注释仅获取第一个/最后一个元素

[英]Fetching only first/last element using Spring Data JPA and @Query annotation

EDIT: Solutions to this problem are provided in the second and fourth answer regarding this question setMaxResults for Spring-Data-JPA annotation? 编辑:有关此问题的第二和第四个答案提供了解决此问题的解决方案有关Spring-Data-JPA注释的setMaxResults?

Goal: Fetch the largest/smallest element by property z using a Spring Data JPA repository and the Spring Query annotation. 目标:使用Spring Data JPA存储库和Spring Query注释,按属性z获取最大/最小元素。

What I have so far 到目前为止我有什么

@Query("SELECT xelement FROM x xelement ORDER BY xelement.z")
public List<X> findFirstElement();

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,我可以使用设置结果的数量

entityManager.setMaxResults(1)

to only get the first element. 只获得第一个元素。

Question: How do I specify the maximum number of results using the @Query annotation? 问题:如何使用@Query注释指定最大结果数?

Idea: Is using a PageRequest of size 0 the way to go? 想法:使用大小为0的PageRequest还是要走的路?

Constraints: I am aware of the "FindFirstBy...." query feature but I want/have to use the @Query annotation. 约束:我知道“FindFirstBy ....”查询功能,但我想/必须使用@Query注释。

You can use the limit property of sql just by adding nativeQuery to @Query annotation. 只需将nativeQuery添加到@Query注释即可使用sql的limit属性。 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注释的情况下解决您的问题:

@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));

Here 1 corresponds to the limit which you want. 这里1对应于您想要的限制。

UPDATE (SPRING DATA 2.0) 更新(春季数据2.0)

Use PageRequest.of(0, 1) instead of new PageRequest(0, 1) 使用PageRequest.of(0,1)而不是新的PageRequest(0,1)

Try to do this: 尝试这样做:

@Query(value = "SELECT xelement FROM x xelement ORDER BY xelement.z  LIMIT 1",
       nativeQuery = true)

The closest JPA query syntax I can think for your use case is findFirstByZIsNotNullOrderByZAsc . 我能为您的用例考虑的最接近的JPA查询语法是findFirstByZIsNotNullOrderByZAsc This should eliminate the need to write custom native query. 这应该消除了编写自定义本机查询的需要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM