Spring, Hibernate and LazyInitializationExceptions

I’ve recently started using Spring for its comprehensive support for Hibernate 3. It makes writing DAOs a snap. There are a couple of wrinkles, however, one is the fact that lazy loading in Hibernate 3 is the default, combined with the fact that Spring will close the Hibernate Session automatically, giving you a LazyInitializationException when you try to access mapped fields from your persistent objects. The solution to this is the “Open Session In View” pattern, which Spring provide a ready-made filter for. Shown below is an extract from my PersistentTestCase, superclass, which all my DAO tests extend, and voila, no more Lazy Exceptions.

protected void setUp() throws ClassNotFoundException, SQLException {
      ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext("application_context.xml");
      factory = (BeanFactoryappContext;
      sessionFactory = (SessionFactory)factory.getBean("test.sessionFactory");
      Session s = sessionFactory.openSession();
      TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(s));  
  protected void tearDown() {
     SessionHolder sessionHolder = (SessionHolderTransactionSynchronizationManager.unbindResource(sessionFactory);
     SessionFactoryUtils.closeSessionIfNecessary(sessionHolder.getSession(), sessionFactory)

Leave a Reply