views:

410

answers:

3

my hibernate object A has object B, C, and D as properties :

A.getB().getName();  
A.getC().getTitle();

now, I want to load A with all its properties without getting a LazyInitializationException. so, I need to load A's object graph fully.

is there any generic method of retrieving an object's graph in hibernate ?

+2  A: 

There are probably times when you want to load the full object graph, and others when you want much less data (and don't want to pay the performance penalty associated with loading all this). So let's suppose your needs varies.

Hibernate lazy load in general, but you can load additional data using one of several methods (see Hibernate documentation for details):

  1. While your session is up (you didn't close it), if you query fields of A, they can be loaded on demand. This is extraordinarily easy and flexible, but can be inefficient if it makes a lot of database calls.
  2. You can create an HQL request to specify that you want to load A, but also some fields. Use FETCH in the query for this.
  3. You can do the same with the Criteria API. Instead of specifying a query, you make method calls.

Sample for lazy :

     A a = ...; // load A
     String name = a.getB().getName(); // triggers an implicit query to load B

Sample for HQL:

     select a 
     from A a
     left join a.b b
     left join a.c c
     where a.id = :id
KLE
+2  A: 

Pattern Open Session in View help avoid LazyInitializationException. Also in Seam it is done by using extended PersistentManager and conversation scope

Antother solution is eager fetching like in this example or KLE answer.

cetnar
+2  A: 

you can specify it in the .hbm.xml mapping file with the attribute 'lazy="false"' or you can specify it in the criteria object with the createAlias or createCriteria methods.

It is also possible to set the fetchMode on a criteria for a specific assocation

Salandur