Announcement Announcement Module
Collapse
No announcement yet.
Is it a right way to initialize in web controller? Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Is it a right way to initialize in web controller?

    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:
    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)
    	}
    }
    MyUtil:
    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);
    	}
    }
    Is it a right way?

  • #2
    If your code solves your problem then it's correct . 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.

    Comment

    Working...
    X