我对Hibernate有点困惑。 我的问题如下:
我的数据库中的表中有一个对象,该对象与不同的注释相关联(存储在另一个表中)
在HQL中,我想在我的表中选择那些对象,但前提是与对象关联的最后一个注释具有特定状态(最后一个注释是具有最高ID的注释)。一条评论只与一个对象相关联。
此请求正常:
select distinct myObject from org.MyClass myInstance
join myObject.comments comment
where comment.status in (:theListOfStatusThatIWant)
但该请求无法满足我的要求......
我试过这个:
select distinct myObject from org.MyClass myInstance
join myObject.comments comment
where comment.status in (:theListOfStatusThatIWant)
order by comment.id desc
但没有成功......(请求工作正常,但没有做我想要的)
有人能帮助我吗?
答案 0 :(得分:3)
你需要表达你想要最后一条评论的事实,如下所示:
select distinct myObject from org.MyClass myInstance
join myObject.comments comment
where comment.status in (:theListOfStatusThatIWant)
and comment.id =
(select max(c1.id) from Comment c1 where c1 member of myObject.comments)
答案 1 :(得分:0)
您的查询的一个初步想法是反转您查询的内容。在伪HQL中:
select c.objectYouReallyWant from Comment c where c.status = ? order by c.id desc
然后,您可以设置maxResults(我相信数据库相关)只返回一行。不幸的是,这只会返回具有正确状态的最后一条评论。如果您想获得最后一条评论,无论状态如何,您都需要删除状态限制。
限制(也称为最大结果)执行时应该比子选择更便宜以找到特定行的最大值),但当然你需要测试它。