Spring CRUD存储库:有没有findOneByMaxXYZColumn()?

Esp*_*sso 28 spring-data

我的要求:

如果VERSION列具有最大值,则从表RETAIN_INFO中获取ONE对象(例如RetainInfo)

CRUD存储库是否支持类似的接口方法

findOneByMaxRetVersionAndCountry("DEFAULT")
Run Code Online (Sandbox Code Playgroud)

等价的db2 sql:

select RET_ID, max(ri.RET_VERSION) from RETAIN_INFO ri  where ri. COUNTRY='DEFAULT'  group by RET_ID  fetch first 1 rows only;
Run Code Online (Sandbox Code Playgroud)
  • 此查询选择一个ID,但我实际上希望RetainInfo对象对应于查询返回的SINGLE行.

我更喜欢不使用自定义查询,即使用findBy或Spring CRUD支持的其他方法/接口.

小智 40

您可以将限制与排序结合使用(弹簧数据引用:限制查询结果).在CrudRepository接口中声明一个类似于以下的方法:

    RetainInfo findTopByCountryOrderByRetVersionDesc(String country);
Run Code Online (Sandbox Code Playgroud)

  • 当在大桌子上跑步时,这开始变得非常昂贵.我用表t` JPQL查询中的`select max(t.field)手动实现了它. (12认同)
  • @MariusSchär:当然你的查询要便宜得多,因为它只搜索最大值。最初的答案是:通过最大列值查找整个实体。因此,您必须使用子查询:`select * from table a where a.column = (select max(b.column) from table b and b.country = a.country) and b.country = "xxx")` (2认同)

Mar*_*ner 9

Spring Data不提供选择最大值的表达式.所有支持的查询部分都可以在Spring 1.2.0.RELEASE文档中找到:附录A.命名空间参考org.springframework.data.repository.query.parser.Part的第182行.

也可以在Spring的Jira页面上创建功能请求.


小智 7

您也可以使用findFirst获得第一个结果。在获得结果之前,请确保先使用Orderby,然后再使用ascending(Asc)或descending(Desc)。例如,如果您要按版本订购并根据productName检索

RetainInfo findFirstByProductNameOrderByVersionDesc(String productName);
Run Code Online (Sandbox Code Playgroud)