HQL顺序由多对多的集合属性组成

时间:2012-10-08 11:21:31

标签: hibernate hql

我有一个名为User的hibernate对象,它与另一个名为Post的hibernate对象有多对多的关系。这种关系称为likedPosts(从User角度来看)。

<set name="likedPosts" lazy="true" table="Likes" where="Deleted=0">
        <cache usage="read-write"/>
        <key column="UserID"/>
        <many-to-many column="PostID" class="Post"/>
    </set>

目前我有一个简单的HQL查询来返回喜欢的帖子列表,如下所示:

"select user.likedPosts from User user where user.id=:uid"

我想要的是这个列表是由Post对象中的属性(特别是帖子ID)排序的。我(天真)尝试这样做的是:

"select user.likedPosts from User user where user.id=:uid 
        order by user.likedPosts.id desc"

这不起作用 - 我得到一个例外,告诉我我不允许这样做。我该怎么做呢?谢谢!

错误的堆栈跟踪:

org.hibernate.QueryException: illegal attempt to dereference collection [user0_.ID.likedPosts] with element property reference [id] [select user.likedPosts from com.pashash.domain.User user where user.id=:uid order by user.likedPosts.id desc]
    at org.hibernate.hql.ast.tree.DotNode$1.buildIllegalCollectionDereferenceException(DotNode.java:46)
    at org.hibernate.hql.ast.tree.DotNode.checkLhsIsNotCollection(DotNode.java:513)
    at org.hibernate.hql.ast.tree.DotNode.resolve(DotNode.java:221)
    at org.hibernate.hql.ast.tree.FromReferenceNode.resolve(FromReferenceNode.java:94)
    at org.hibernate.hql.ast.tree.FromReferenceNode.resolve(FromReferenceNode.java:90)
    at org.hibernate.hql.ast.HqlSqlWalker.resolve(HqlSqlWalker.java:728)
    ...

1 个答案:

答案 0 :(得分:6)

您需要显式联接来执行此操作:

select post from User user
inner join user.likedPosts post
where user.id = :userId
order by post.id desc