我有Hibernate HQL查询,它似乎完美地完成了它的工作,但我目前正在尝试使用Hibernate Criteria API,并希望用Criteria API表达相同的HQL查询 . 在这个特定的例子中,我在HQL查询中有两个连接,其中我的第二个连接使用来自我的第一个连接的别名 . 我想实现与Criteria API相同的东西 . 这可能吗?
这是原始查询:
select mt
from MessageThread mt
inner join mt.messageThreadsStatuses ts
inner join ts.threadLocations tl
where ts.user.userId = :userId and tl = 0";
这是重写的查询,这对我不起作用:
Criteria c = sf.getCurrentSession().createCriteria(MessageThread.class)
.createAlias("messageThreadsStatuses", "ts").setFetchMode("ts", FetchMode.JOIN)
.createAlias("ts.threadLocations", "tl").setFetchMode("tl", FetchMode.JOIN)
.add(Restrictions.eq("ts.user.userId", userId))
.add(Restrictions.eq("tl", 0));
我也尝试过将第二个别名定义为:
.createAlias("threadLocations", "tl").setFetchMode("tl", FetchMode.JOIN)
但没有成功 .
1 回答
如以下文档http://billingb.livejournal.com/34266.html所示:
如果您使用别名和您创建的每个条件对象,则很容易解决这两个问题 . 我认为最大的错误是,大多数示例都显示了所有标准创建链接在一起,但您可以将它们分开,一切都变得更容易理解 . 我想出的解决方案代码如下: