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
Hibernate Criteria and multiple join
提问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
, B
and C
classes, correspondingly (class A
has attribute b
and so on).
注意:"b"
,"c"
和"d"
在上面的代码中指的是A
,B
和C
类中的属性名称,对应地(类A
有属性b
等等)。
For this solution you don't even need to have lazy
and fetch
parameters to be set in your A.hbm.xml
.
对于此解决方案,你甚至都不需要有lazy
和fetch
参数,在您的设置A.hbm.xml
。
回答by Péter T?r?k
回答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:
是的,实际上有几种方法可以做到这一点:
- When mapping the association, set its lazyness to false and its fetch mode to join. This will affect all criteria queries.
- Use setFetchMode as detailed by the other answers.
- Use criteria.createAlias (or createCriteria). This also allows you to further restrict the rows you want joined.
- 在映射关联时,将其惰性设置为 false 并将其获取模式设置为加入。这将影响所有条件查询。
- 使用其他答案详述的 setFetchMode 。
- 使用criteria.createAlias(或createCriteria)。这还允许您进一步限制要加入的行。