Lazy initialization with Hibernate and Spring

If are new to Hibernate and Spring, you may have come across the following exception:


net.sf.hibernate.LazyInitializationException Failed to lazily initialize a
collection - no session or session was closed

This problem surfaces when you try to create a hibernate mapping to model a parent child association so that the database query to get the children is executed only when you attempt to access the set of children (and not before). This is the so called lazy initialization of a collection, the alternative is to perform eager initialization where the query to get the children is executed when the parent object is created.

To get lazy initialization to work, you need to understand how to configure Spring, how to create the correct hibernate mapping files, and in particular, the life cycle of the hibernate session object.

Spring provides a number of abstractions to make working with hibernate easier and more efficient. With respect to hibernate sessions, Spring offers a number of options depending on whether you’re writing a servlet or not. In the case of the servlet, you can use Spring’s OpenSessionInViewFilter class which ensures that the hibernate session is attached to the thread that is processing the entire HTTP request. If you’re writing an application or a JUNIT test case, for example, then you need to ensure that transaction synchronization is happening per thread. See the JUNIT setUp and tearDown methods here for how to do this.

I started writing a sample hibernate/spring application to test how lazy initialization and cascaded deletes work. The sources of this sample can be accessed here. Whist I was doing this work, I came across this excellent description on how to test hibernate and spring.

Advertisement

2 Responses to “Lazy initialization with Hibernate and Spring”

  1. Muthu Says:

    Hi,
    I’m new to Hibernate and Springs. Can you give a complete code for the above scenario. This would be helpful for beginners like me to analyse the solution better.

    Cheers,
    Muthu

  2. sj Says:

    Hello Muthu,

    The source is available. Please see the links to the source in my other entry on Spring and Hibernate.

Leave a Reply

Fill in your details below or click an icon to log in:

Gravatar
WordPress.com Logo

Please log in to WordPress.com to post a comment to your blog.

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s


Follow

Get every new post delivered to your Inbox.