zoukankan      html  css  js  c++  java
  • 关于Web项目出现懒加载异常的解决方案

    manytomany关系中,使用 fetch = FetchType.LAZY 来做懒加载,加快些性能。但是却一直出错,原因是session被关闭,要保持session,需要事务。

    • Hibernate
    1. 使用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>
    2. 使用的是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
    1. 使用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>
    2. 使用的是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;
      }
  • 相关阅读:
    【转载】STL之priority_queue
    数据结构作业——直通车(并查集)
    Codeforces Round #342 (Div. 2) D. Finals in arithmetic(想法题/构造题)
    Size Balance Tree(SBT模板整理)
    平衡二叉查找树(AVL)的理解与实现
    查找树ADT——二叉搜索树
    (转载)通过金矿模型介绍动态规划
    动态规划(DP)基础
    hdu 1969 Pie(二分查找)
    poj 3104 Drying(二分查找)
  • 原文地址:https://www.cnblogs.com/onlymate/p/7543504.html
Copyright © 2011-2022 走看看