通过相关对象的最大日期限制Hibernate查询

时间:2015-01-21 20:12:59

标签: hibernate

我有一个包含许多Box类的Shelf类,而Box类有许多Specimen类。在Specimen类中是catalogDate的属性。

我要做的是找到max catalogDate所在的所有货架。

如何执行必要的查询?我尝试了几种方法,但我找不到的任何方法实际上都表现出同样的壮举。

充其量我可以预测所有Specimen实例的最大值,但是,从头开始,所有实例都是。

编辑我可以通过SQL执行我想要的工作

  select shelf.id
        ,max(specimen.catalogDate)
   from shelf_tbl shelf
   inner join box_tbl box
   on shelf.id = box.shelf_id
   inner join specimen_tbl specimen
   on box.specimen_id = specimen.id
   group by shelf.id

1 个答案:

答案 0 :(得分:0)

你应该使用连接。如果您已经映射了关系,则可以编写如下查询:

select 
       shelf,
       max(specimen.catalogDate) 
from 
   Shelf as shelf join 
   shelf.box as box join 
   box.specimen as specimen 

你应该添加一个group by子句,其中包含Shelf的所有属性

如果你想要自己带有最新的样本目录日期,你应该添加

where specimen.catalogDate = (select max(catalogDate) from Specimen)