SpringDataJpa -- NoSession问题分析和解决

前言:对SpringDataJpa NoSession问题进行分析和解决。

一、问题分析

1、为什么会出现NoSession?
① 从字面理解NoSession的原因是没有获取到Session,那为什么获取不到Session了,通常在Service层中所有Dao层操作完毕提交事务后,Session就会被关闭。在此时如果再次执行Dao层操作就必须获取Session,但是Session已经关闭所有就会报NoSession。

2、为什么会出现Dao查询之后会再次出现Dao操作呢?
Hibernate出现NoSession问题的原因:
Hibernate NoSession博客地址

通过Hibernate出现NoSession问题的原因可以得出此结论:
SpringDataJpa在数据库查询中同样也有延迟加载,而在SpringDataJpa中查询集合属性时为延迟加载。

三、解决方案

1、既然是延迟加载那么就可以让其立即加载,但是并不适用。因为立即加载会使一次查询时间较长,影响查询效率。
立即加载注解属性:fetch=FetchType.EAGER
@ManyToMany(mappedBy = “couriers”,fetch=FetchType.EAGER//立即加载)

2、在web.xml中配置View层获取当前线程绑定Session的过滤器。

<!-- 在View层获取当前线程绑定的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>

注意:配置OpenEntityManagerInViewFilter时必须要在struts2核心过滤器之前。

猜你喜欢

转载自blog.csdn.net/m0_37602117/article/details/79771350