环境:springmvc 3.2.6 + spring-data-jpa 1.4.3 + hibernate 4.3.1
报错:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.LazyInitializationException: could not initialize proxy - no Session at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:948) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:827) at javax.servlet.http.HttpServlet.service(HttpServlet.java:687) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)....
Caused by: org.hibernate.LazyInitializationException: could not initialize proxy - no Session at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:164) at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:285) at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:185)
解决方法:
Spring-Data-Jpa用的是jpa实现,要用OpenEntityManagerInViewFilter,Java-Config(web.xml请自行转换)代码如下
...
import org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter;
...
public class ApplicationInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext)
throws ServletException {
....
FilterRegistration.Dynamic openEntityManagerInViewFilter = servletContext.addFilter("openEntityManagerInViewFilter", OpenEntityManagerInViewFilter.class);
openEntityManagerInViewFilter.setInitParameter("entityManagerFactoryBeanName","entityManagerFactory");
openEntityManagerInViewFilter.addMappingForUrlPatterns(null, false, "/*");
...
}
}
附:Spring针对Hibernate的非JPA实现,用的是OpenSessionInViewFilter。