getCurrentSession 与 openSession() 的区别及hibernate lazy加载异常

本文探讨了Hibernate框架中使用getCurrentSession与openSession的区别,包括它们在事务管理、资源释放方面的不同行为,以及如何解决lazy加载时可能出现的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

* 采用getCurrentSession()创建的session会绑定到当前线程中,而采用openSession()

创建的session则不会

* 采用getCurrentSession()创建的线程会在事务回滚或事物提交后自动关闭, sessioncommitrollback时会自动关闭,而采用openSession()

创建的session必须手动关闭

 

Hibernate配置:

这里getCurrentSession本地事务(本地事务:jdbc)要在配置文件里进行如下设置

l      如果使用的是本地事务(jdbc事务)

l       <propertyname="hibernate.current_session_context_class">thread</property>
 *
如果使用的是全局事务(jta事务)
 <property name="hibernate.current_session_context_class">jta</property> 


Hibernate异常:could not initialize proxy no session 


Hibernate在使用lazy加载的时候,如果使用getCurrentSession()就会有问题,原因是getCurrentSession()在创建的线程会在事务回滚或事务提交后自动关闭,所以在执行user.getUsername()session已经关闭,而我们此时还想再去数据库查询具体的user会报错。

解决方法:

1、通过我们手动操作session,也就是我们利用openSession(),这样在我们每次调用结束后再关闭session,切记一定要关闭session

2、我们不选用lazy的方法,用eager,就是并发加载,同时将所有关联的表都加载好

3、使用OpenSessionInViewFilter。这种方法是将session交给servlet filter来管理,每当一个请求来之后就会开启一个session,只有当响应结束后才会关闭。如下:

<filter-name>hibernateFilter</filter-name>
<filter-class>  org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>          </filter> 
        <filter-mapping>
              <filter-name>hibernateFilter</filter-name>
              <url-pattern>/*</url-pattern>
         </filter-mapping>
 

<filter>

      <filter-name>OpenSessionInViewFilter</filter-name>

      <filter-class>

         org.springframework.orm.hibernate3.support.OpenSessionInViewFilter

      </filter-class>

       </filter>

上面的配置文件时在web.xml中配置的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值