对弹簧数据jpa进行排序和限制

时间:2014-06-04 07:08:58

标签: spring-data-jpa

假设我有一个 cats 的存储库 weight 属性,如果我想找到最重的猫我必须这样做:

Page<Cat> cats = catRepository.findAll(new PageRequest(0, 1, Sort.Direction.DESC), "weight");
Iterator<Cat> it = cats.iterator();
if(cats.hasNext()) {
  Cat heaviest = it.next();
} else {
}

不支持尝试简单地将Cat findOneOrderByWeightDesc()放在存储库接口上。

在弹簧数据jpa上有没有更简单的方法来实现这个目标?


2014年7月5日编辑:Thomas Darimont亲切地实施了一项解决上述问题的新功能:http://jira.spring.io/browse/DATACMNS-516

2 个答案:

答案 0 :(得分:1)

List<Cat> findAllByOrderByWeightDesc();

应该可以正常工作。

答案 1 :(得分:0)

在这种情况下,您可以使用本机查询:

这适用于每个数据库:

@Query(value = "select a.* from #{#entityName} a LEFT JOIN #{#entityName} b ON a.id = b.id AND a.weight < b.weight WHERE b.id IS NULL", nativeQuery = true)
Iterable<Cat> findHeaviestCat1();

这是一个特定于mysql的变体:

@Query(value = "select a.* from #{#entityName} a LEFT JOIN #{#entityName} b ON a.id = b.id AND a.weight < b.weight WHERE b.id IS NULL limit 1", nativeQuery = true)
Cat findHeaviestCat2();
相关问题