问题
Spring version is 2.4.0
.
I have a PlayerEntity
with Integer totalRacesCount
field. I need to make the top of players of different top length ordered by totalRacesCount
desc. Top size must vary.
I am trying to add a method in my CrudRepository<PlayerEntity, Long>
to implement this.
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.limit-query-result — this section states that we can pass a numeric value top
to make the limit parameterizable. This is working, but only when not combined with OrderByTotalRacesCountDesc
, i.e. it works for Asc
sorting.
- Method for a single top 1 record, without
top
parameter is working:PlayerEntity findTopByOrderByTotalRacesCountDesc();
— selects player with maximaltotalRacesCount
, everything correct. - Method for a hardcoded top N records is also working:
List<PlayerEntity> findTop25ByOrderByTotalRacesCountDesc();
— returns 25 players with highesttotalRacesCount
. - However, when I try to add an
int top
parameter:List<PlayerEntity> findTopByOrderByTotalRacesCountDesc(int top);
, start of the application fails with non-expecting thetop
parameter:
java.lang.IllegalArgumentException: Failed to create query for method public abstract java.util.List parser.repository.PlayerRepository.findTopByOrderByTotalRacesCountDesc(int)! At least 1 parameter(s) provided but only 0 parameter(s) present in query.
- I've also tried to omit
By
afterTop
:List<PlayerEntity> findTopOrderByTotalRacesCountDesc(int top);
, but this obviously is an incorrect syntax and fails on treatingDesc
as property name:
java.lang.IllegalArgumentException: Failed to create query for method public abstract java.util.List parser.PlayerRepository.findTopOrderByTotalRacesCountDesc(int)! No property desc found for type Integer!
I know I can implement the @Query
and set top
as a @Param
. But is it possible to implement the task with the query auto-generated by method name? The behavior looks like a bug actually.
All the links I've found use @Query
(JPA or native) to implement the order by desc
sorting.
回答1:
Looks like I was reading the documentation incorrectly:
You can append an optional numeric value to top or first to specify the maximum result size to be returned.
This actually DOES NOT mean a "method parameter" that you can vary, but just a hard-coded number after Top
in the method name.
Solution: I should use setMaxResults
instead.
来源:https://stackoverflow.com/questions/65366365/spring-repository-auto-generated-method-select-by-given-top-number-order-by-f