Andrea Scarafoni
Andrea Scarafoni

Reputation: 955

Hibernate Criteria and multiple join

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;

Upvotes: 13

Views: 49553

Answers (4)

Rachel
Rachel

Reputation: 3711

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.

Upvotes: 3

mindas
mindas

Reputation: 26733

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.

Upvotes: 18

meriton
meriton

Reputation: 70584

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.

Upvotes: 0

Péter Török
Péter Török

Reputation: 116306

Try setting the fetch mode in your criteria, like:

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

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

Upvotes: 1

Related Questions