manytomany关系中,使用 fetch = FetchType.LAZY 来做懒加载,加快些性能。但是却一直出错,原因是session被关闭,要保持session,需要事务。
- Hibernate
- 使用xml配置文件
<!-- 配置opensessionInViewFilter 用于解决懒加载问题--> <filter> <filter-name>OpenSessionInViewFilter</filter-name> <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class> </filter> <filter-mapping> <filter-name>openSessionInViewFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
- 使用的是Java配置
/** * 处理hibernate的懒加载异常,延长hibernate的session再回话结束后关闭 * @Title: customOpenEntityManagerInViewFilter * @Description: TODO * @return FilterRegistrationBean * @throws */ @Bean public FilterRegistrationBean OpenSessionInViewFilter() { FilterRegistrationBean registration = new FilterRegistrationBean(); registration.setFilter(new OpenSessionInViewFilter()); registration.addUrlPatterns("/*"); registration.setName("openSessionInViewFilter"); registration.setOrder(1);//设置优先级,必须大于shiro的fiter,不然会出现session周期的问题 return registration; }
- JPA
- 使用xml配置文件
<!--在页面开启session,解决懒加载异常的问题--> <filter> <filter-name>OpenEntityManagerInViewFilter</filter-name> <filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class> </filter> <filter-mapping> <filter-name>openEntityManagerInViewFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
- 使用的是Java配置
/** * @Description: 处理JPA的懒加载异常,延长hibernate的session再回话结束后关闭 * @Title: customOpenEntityManagerInViewFilter * @throws * @return FilterRegistrationBean */ @Bean public FilterRegistrationBean customOpenEntityManagerInViewFilter() { FilterRegistrationBean registration = new FilterRegistrationBean(); registration.setFilter(new OpenEntityManagerInViewFilter()); registration.addUrlPatterns("/*"); registration.setName("openEntityManagerInViewFilter"); registration.setOrder(1);// 设置优先级,必须大于shiro的fiter,不然会出现session周期的问题 return registration; }