【问题标题】:HQL query with two joins expressed in Criteria API使用 Criteria API 表示的具有两个连接的 HQL 查询
【发布时间】:2012-08-19 17:56:55
【问题描述】:

我有 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)

但没有成功。

【问题讨论】:

  • 它在做什么?有错误信息吗?

标签: hibernate hql


【解决方案1】:

如下文http://billingb.livejournal.com/34266.html所示:

如果您使用别名和您创建的每个条件对象,解决这两个问题很容易。我认为最大的错误是大多数示例将所有标准创建链接在一起,但是您可以将它们分开,一切都变得更容易理解。我想出的解决方案代码如下:

Criteria c = session.createCriteria(Parameter.class);
Criteria cx = c.createCriteria("masterCollections");
cx.createAlias("datasetEntry", "de");
cx.createAlias("parameters", "par");
c.add(Restrictions.or(Restrictions.in("de.datasetId",datasetIDList), Restrictions.in("par.parameterId", parameterIDList)));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-24
    • 1970-01-01
    • 2012-08-20
    • 2018-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多