问题
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