views:

639

answers:

3

Are there any other ways to avoid LazyInitializationExceptions in a Hibernate web application besides using the OpenSessionInView pattern? Are there any downsides to using OpenSessionInView?

+6  A: 

When working on our web applications, we usually decide beforehand which objects/fields will be needed in the view pages and make sure that all the objecs are properly initialized from the model before dispatching to the view.

This can be accomplished in (at least) three ways:

  1. fetching properties using eager strategy (i.e. with FetchMode.JOIN, if you're using the Criteria API)
  2. explicitly initializing properties (i.e. with Hibernate.initialize(property)
  3. implicitly initializing properties by calling the appropriate property accessor

About the downsides of OpenSessionInView, have you checked out this page?

abahgat
+4  A: 

Typically the best way to handle the problem, without making a global decision to do eager fetching; is to use the "fetch" keyword in conjuction with the hql query.

From http://www.hibernate.org/hib_docs/reference/en/html/queryhql-joins.html

In addition, a "fetch" join allows associations or collections of values to be initialized along with their parent objects, using a single select. This is particularly useful in the case of a collection. It effectively overrides the outer join and lazy declarations of the mapping file for associations and collections. See Section 19.1, “Fetching strategies” for more information.

from Cat as cat inner join fetch cat.mate left join fetch cat.kittens

+1  A: 

Switch to JBoss Seam.

The Seam framework is well architected by the guys that developed Hibernate.

Even with the Open Session in View, you may still have some problems. Depending on how complex your web application is, Open Session In View does not handle all cases. I've had issues with displaying data as well (in the UI) as fetching entities during a quartz job such as sending an email.

Hibernate already intelligently fetches data, changing the fetch mode will result in performance degradation. Not only that, but you are getting away from convention and will muck up your project with extraneous configuration details.

Walter