Spring Repository auto-generated method: select by given top number + order by field desc

北城以北 提交于 2021-01-29 08:08:33

问题


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 maximal totalRacesCount, everything correct.
  • Method for a hardcoded top N records is also working: List<PlayerEntity> findTop25ByOrderByTotalRacesCountDesc(); — returns 25 players with highest totalRacesCount.
  • However, when I try to add an int top parameter: List<PlayerEntity> findTopByOrderByTotalRacesCountDesc(int top);, start of the application fails with non-expecting the top 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 after Top: List<PlayerEntity> findTopOrderByTotalRacesCountDesc(int top);, but this obviously is an incorrect syntax and fails on treating Desc 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!