有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JavaSpring存储库自动生成方法:按给定的顶部编号+按字段描述排序选择

Spring版本是2.4.0

我有一个带有Integer totalRacesCount字段的PlayerEntity。我需要按照totalRacesCountdesc的顺序排列不同长度的玩家的顶部。顶部大小必须不同

我试图在我的CrudRepository<PlayerEntity, Long>中添加一个方法来实现这一点

https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.limit-query-result-本节说明我们可以传递一个数值top,以使限制参数化。这是可行的,但只有在不与OrderByTotalRacesCountDesc结合使用时,也就是说,它适用于Asc排序

  • 没有top参数的单个前1条记录的方法正在工作:PlayerEntity findTopByOrderByTotalRacesCountDesc();-选择具有最大totalRacesCount的播放器,一切正常
  • 硬编码的前N个记录的方法也起作用:List<PlayerEntity> findTop25ByOrderByTotalRacesCountDesc();-返回25个具有最高totalRacesCount的播放器
  • 但是,当我尝试添加int top参数:List<PlayerEntity> findTopByOrderByTotalRacesCountDesc(int top);时,应用程序启动失败,不需要top参数:
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.
  • 我还尝试在Top:List<PlayerEntity> findTopOrderByTotalRacesCountDesc(int top);之后省略By,但这显然是一种不正确的语法,无法将Desc作为属性名:
 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!

我知道我可以实现@Query并将top设置为@Param。但是,是否可以通过方法名自动生成的查询来实现任务该行为实际上看起来像一个bug

我发现的所有链接都使用@Query(JPA或native)来实现order by desc排序


共 (1) 个答案

  1. # 1 楼答案

    看起来我没有正确阅读文档:

    You can append an optional numeric value to top or first to specify the maximum result size to be returned.

    这实际上并不意味着可以改变的“方法参数”,而只是方法名Top后面的硬编码数字

    解决方案:我应该使用setMaxResults