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 = (BeanFactory) appContext;
sessionFactory = (SessionFactory)factory.getBean("test.sessionFactory");
Session s = sessionFactory.openSession();
TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(s));
}
protected void tearDown() {
SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.unbindResource(sessionFactory);
SessionFactoryUtils.closeSessionIfNecessary(sessionHolder.getSession(), sessionFactory);
}
|
This entry was posted
on Thursday, April 28th, 2005 at 4:32 pm and is filed under Coding.
You can follow any responses to this entry through the RSS 2.0 feed.
You can leave a response, or trackback from your own site.