In order to avoid LazyInitializationException, while running a JUnit test that uses Spring Framework, following is required as part of setUp() method of the testcase.
@Override
public void setUp(){
appContext = new ClassPathXmlApplicationContext(new String[]{"/appDataContext.xml", "/appServiceContext.xml"});
EntityManagerFactory emf = (EntityManagerFactory) appContext.getBean("entityManagerFactory", EntityManagerFactory.class);
EntityManager em = createEntityManager(emf);
TransactionSynchronizationManager.bindResource(emf, new EntityManagerHolder(em));
}
Above binds the EntityManager to the current thread, ensuring that it is not closed, which enables next service / dao call to execute successfully.
April 2008
Monthly Archive
Thu 17 Apr 2008
Spring Framework, JPA, JUnit and LazyInitializationException…
Posted by manishn under JavaNo Comments