Hibernate Criteria and multiple join

匿名 (未验证) 提交于 2019-12-03 02:14:01

问题:

is possible with Hibernate criteria do it?

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; 

回答1:

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).

For this solution you don't even need to have lazy and fetch parameters to be set in your A.hbm.xml.



回答2:

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

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 stragies that may be of use to you.



回答3:

Try setting the fetch mode in your criteria, like:

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

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



回答4:

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.


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!