Friday, 12 January 2007

Spring, Hibernate, Lazy Loading, and Sessions

Recently I've developed a Spring application to notify users based on certain conditions on data extracted from an ERP system using Hibernate. I had a LazyInitializationException problem when looping through some hibernate objects, because the connection had already been closed i.e. The service layer had finished it's job and therefore closed the connection. The hibernate object became detached, and since I specified lazy to true, I got the LazyInitializationException.

Since it is not a web app, I cannot use OpenInSessionViewInterceptor or OpenInSessionViewFilter, so I figured out that I had to use some manual code to keep the session open. Here is the code to solve the issue:

private static SessionFactory sessionFactory;
private static ApplicationContext init() {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
sessionFactory = (SessionFactory) context.getBean("sessionFactory");
Session session = SessionFactoryUtils.getSession(sessionFactory, true);
TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
return context;

private static void end() {
if (sessionFactory != null) {
SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.unbindResource(sessionFactory);

blog comments powered by Disqus