Java 休眠条件和多重连接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2252468/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 05:15:29  来源:igfitidea点击:

Hibernate Criteria and multiple join

javahibernatejoincriteria

提问by Andrea Scarafoni

is possible with Hibernate criteria do it?

可以用 Hibernate 标准来做吗?

select A.something, B.something, C.something, D.something
    from  A JOIN B on A.id = B.id_fk
          JOIN C ON B.id = C.id_fk
          JOIN D ON C.id = D.id_fk;

采纳答案by mindas

I have got exactly the same problem, and was able to resolve it like this:

我遇到了完全相同的问题,并且能够像这样解决它:

return criteria.createCriteria(A.class)
               .createCriteria("b", "join_between_a_b")
               .createCriteria("c", "join_between_b_c")
               .createCriteria("d", "join_between_c_d")
               .add(Restrictions.eq("some_field_of_D", someValue));

Note: "b", "c"and "d"in code above refer to attribute names in A, Band Cclasses, correspondingly (class Ahas attribute band so on).

注意:"b","c""d"在上面的代码中指的是A,BC类中的属性名称,对应地(类A有属性b等等)。

For this solution you don't even need to have lazyand fetchparameters to be set in your A.hbm.xml.

对于此解决方案,你甚至都不需要有lazyfetch参数,在您的设置A.hbm.xml

回答by Péter T?r?k

Try setting the fetch mode in your criteria, like:

尝试在您的标准中设置获取模式,例如:

criteria.setFetchMode(..., FetchMode.EAGER)

This creates a join query. You may find more details here.

这将创建一个连接查询。您可以在此处找到更多详细信息。

回答by Rachel

There are some good examples in the Hibernate Reference materialthat show to use setFetchMode to fetch associations with an outer join.

Hibernate 参考资料中有一些很好的例子,说明如何使用 setFetchMode 来获取与外部联接的关联。

An example is:

一个例子是:

List books = sess.createCriteria(Book.class)
.setFetchMode("chapters", FetchMode.EAGER)
.setFetchMode("reviews", FetchMode.EAGER)
.list();

There is also information there about different fetching stragiesthat may be of use to you.

那里还有关于可能对您有用的不同获取策略的信息

回答by meriton

Yes, in fact there are several ways of doing this:

是的,实际上有几种方法可以做到这一点:

  1. When mapping the association, set its lazyness to false and its fetch mode to join. This will affect all criteria queries.
  2. Use setFetchMode as detailed by the other answers.
  3. Use criteria.createAlias (or createCriteria). This also allows you to further restrict the rows you want joined.
  1. 在映射关联时,将其惰性设置为 false 并将其获取模式设置为加入。这将影响所有条件查询。
  2. 使用其他答案详述的 setFetchMode 。
  3. 使用criteria.createAlias(或createCriteria)。这还允许您进一步限制要加入的行。