views:

7461

answers:

4

I am working on a project for a customer who wants to use lazy initialization. They always get "lazy initialization exception" when mapping classes with the default lazy loading mode.

@JoinTable(name = "join_profilo_funzionalita", joinColumns = {@JoinColumn(name =    "profilo_id", referencedColumnName = "profilo_id")}, inverseJoinColumns = {@JoinColumn(name = "funzionalita_id", referencedColumnName = "funzionalita_id")})
//@ManyToMany(fetch=FetchType.EAGER) - no exceptions if uncommented
@ManyToMany 
private Collection<Funzionalita> funzionalitaIdCollection;

Is there a standard pattern using JPA classes to avoid this error?

Snippets are welcome, thanks a lot for your time.

+1  A: 

OpenSessionInView is one pattern to deal with this problem. Some info here:

http://www.hibernate.org/43.html

What kind of application are you writing? If you're not dealing with remoting (no web services, no AJAX-based web client) then OSIV may work very nicely. Otherwise things get complicated quickly...

cliff.meyers
A: 

LazyInitializationException means that you are calling the collection after the hibernate session has closed, or after the object has been detached from the session.

You need to either re-attach the object to hibernate session, change the place where you are calling the collection, or move the boundary of where the session gets closed to a higher layer.

Daniel Alexiuc
A: 

There are many ways to pre-fetch properties, so they are there after session is closed:

  1. Just call appropriate getter. After field is fetched into bean it is there after session is closed.
  2. You may initialize field in EJBQL query , look for JOIN FETCH keyword.
jb
A: 

Using JBoss Seam solves the problem LazyInitailizationException and not only. Seam does not close the hibernate session after each request but it binds to the conversation (Open session in Conversation) so you can really use the dirty checking in the long conversations like wizards (no merge only flash). View rendering phase is executed in a separate transaction so there is no problem if the commit fails as in OpenSessionInView.

hoke