Configuring web.xml in a Spring MVC with Hibernate project.DispatcherServlet and ContextLoaderListener have each a sessionFactory

时光怂恿深爱的人放手 提交于 2019-12-08 05:55:23

问题


Like the title says, am about to configure a Spring MVC project with Hibernate/JPA for persistence.

I remember I used the same context for both DispatcherServlet and ContextLoaderListener until recently I've being advised to separate them. But in separating the I've found out that both were loading a SessionFactory making my OpenSessionInViewFilter a pain then I've separated the concerns, leaving only MVC concerns to the DispatcherServlet.

Aside having a mechanism to load collections when needed, when calling this parent objects, what are the other tips to avoid the infamous LazyInitializationException?


回答1:


If your "unit of work" cannot be automatically per request, I think you can create it manually in your service layer using a transaction. Something like this:

public Object serviceMethod(params) {
   TransactionTemplate transactionTemplate; 
   transactionTemplate.execute(new TransactionCallbackWithoutResult() {
         public void doInTransactionWithoutResult(TransactionStatus status) {
         try {
        // call your DAO's to update/delete/... and set values to service
         } catch (DAOException e) {
        LOGGER.error(e);
        throw new ServiceException(e);
         }
    }
});
}


来源:https://stackoverflow.com/questions/12313840/configuring-web-xml-in-a-spring-mvc-with-hibernate-project-dispatcherservlet-and

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!