13

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;
skaffman
  • 398,947
  • 96
  • 818
  • 769
Andrea Scarafoni
  • 937
  • 2
  • 13
  • 26

4 Answers4

18

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.

mindas
  • 26,463
  • 15
  • 97
  • 154
3

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.

Gray
  • 115,027
  • 24
  • 293
  • 354
Rachel
  • 3,691
  • 5
  • 32
  • 32
  • Actually this didn't work for me, I had to do it like in the answer I have posted. It could be because I had an extra criteria on the `D`. – mindas Feb 23 '11 at 18:19
  • `FetchMode.EAGER` is deprecated nowadays, use `FetchMode.JOIN` instead. – Tim Büthe Aug 13 '19 at 16:23
1

Try setting the fetch mode in your criteria, like:

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

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

Péter Török
  • 114,404
  • 31
  • 268
  • 329
0

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.
meriton
  • 68,356
  • 14
  • 108
  • 175