I know that have some solutions to init lazy collection in spring(hibernate).
Some thing like OpenSessionInView pattern or touch POJO inside DAO or transaction.
But I want to init lazy collection in the web controller(spring MVC).
That's my solution.
Spring MVC:
MyUtil:Code:public class MyFormContrller extends SimpleFormController { public Map referenceData(HttpServletRequest request) { Item item = service.getItem(); Set Bids = item.getBids(); // bids is lazy, iterate bids will cause LazyInitializtionException MyUtil.initialize(item, bids); // bids is initiated, so we can use it in view (jsp) } }
Is it a right way?Code:public class MyUtil { public static void initialize(Object parent, Collection children) { SessionFactory sessionFactory= (SessionFactory) fCtx.getBean("sessionFactory"); Session session = sessionFactory.openSession(); TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session)); session.update(parent); Hibernate.initialize(children); SessionHolder holder = (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory); session = holder.getSession(); session.flush(); TransactionSynchronizationManager.unbindResource(sessionFactory); SessionFactoryUtils.closeSessionIfNecessary(session, sessionFactory); } }


Reply With Quote
. OpenSessionInView is nice because you don't have to worry about lazy-init problem even if you are inside the view (Spring MVC in you case) - the session is going to be closed after the view is generated/rendered.
