4.4.5. Limiting Query Results
You can limit the results of query methods by using the first
or top
keywords, which you can use interchangeably. You can append an optional numeric value to top
or first
to specify the maximum result size to be returned. If the number is left out, a result size of 1 is assumed. The following example shows how to limit the query size:
Example 18. Limiting the result size of a query with Top
and First
User findFirstByOrderByLastnameAsc();
User findTopByOrderByAgeDesc();
Page<User> queryFirst10ByLastname(String lastname, Pageable pageable);
Slice<User> findTop3ByLastname(String lastname, Pageable pageable);
List<User> findFirst10ByLastname(String lastname, Sort sort);
List<User> findTop10ByLastname(String lastname, Pageable pageable);
The limiting expressions also support the Distinct
keyword for datastores that support distinct queries. Also, for the queries that limit the result set to one instance, wrapping the result into with the Optional
keyword is supported.
If pagination or slicing is applied to a limiting query pagination (and the calculation of the number of available pages), it is applied within the limited result.
| Limiting the results in combination with dynamic sorting by using a |
https://docs.spring.io/spring-data/jpa/docs/2.7.15/reference/html/#repositories.limit-query-result
2023-08-23 09:38:19.597 [main] INFO o.h.hql.internal.QueryTranslatorFactoryInitiator - HHH000397: Using ASTQueryTranslatorFactory
Hibernate:
select
checkconte0_.id as id1_1_,
checkconte0_.checkResult as checkRes2_1_,
checkconte0_.createTime as createTi3_1_,
checkconte0_.fileMd5 as fileMd4_1_,
checkconte0_.fileName as fileName5_1_,
checkconte0_.paramType as paramTyp6_1_,
checkconte0_.requestParam as requestP7_1_,
checkconte0_.resultJson as resultJs8_1_,
checkconte0_.transferResult as transfer9_1_
from
CheckContentEntity checkconte0_
where
checkconte0_.fileName=?
and checkconte0_.paramType=? limit ?
CheckContentEntity(id=3117759, requestParam=https://s.cn.bing.net/th?id=OHR.SkogafossWaterfall_ZH-CN4763253095_1920x1080.webp&qlt=50, paramType=2, fileName=image.jpg, fileMd5=571903dd289ff0d6fb93bbb399cb9572, checkResult=1, resultJson={"conclusion":"合规","log_id":16919943910398412,"isHitMd5":false,"conclusionType":1}, createTime=2023-08-14T14:26:34, transferResult=null)
Hibernate:
select
checkconte0_.id as id1_1_,
checkconte0_.checkResult as checkRes2_1_,
checkconte0_.createTime as createTi3_1_,
checkconte0_.fileMd5 as fileMd4_1_,
checkconte0_.fileName as fileName5_1_,
checkconte0_.paramType as paramTyp6_1_,
checkconte0_.requestParam as requestP7_1_,
checkconte0_.resultJson as resultJs8_1_,
checkconte0_.transferResult as transfer9_1_
from
CheckContentEntity checkconte0_
where
checkconte0_.requestParam=?
and checkconte0_.paramType=? limit ?
null