Hibernate Criteria and multiple join

2020-01-30 07:47发布

问题:

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.