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.