hibernate的getSession和getCurrentSession源码解析

Hibernate

  1. openSession

测试代码:

./image0.bmp

1)sf.openSession()时,sessionFactorynew一个新的Session,从配置中读取是否要自动关闭Session,而配置中默认isAutoCloseSessionEnabledfalse./image1.bmp

2)session.getTransaction().commit(),提交事务

./image2.bmp

3)提交完成或回滚完成以后,会执行一个方法closeIfRequired();在该方法里面去关闭session,关闭session之前又一个判断transactionContext.shouldAutoClose();

./image3.bmp

  1. transactionContext.shouldAutoClose()中,判断autoCloseSessionEnabled,而这个值,在sf.openSession()时,已经被设成了false,故在提交完成以后,无法关闭,需要手动关闭。

./image4.bmp

./image5.bmp



2.getCurrentSession

测试代码:

./image6.bmp

  1. sf.getCurrentSession();

./image7.bmp

这里session和线程绑定的细节如下:

./image8.bmp

在方法currentSession中,首先去当前线程中取session,若没有,则继续bindOrObtainSession();

  1. bindOrObtainSession()中,调用了SessionImpl的另一个openSession方法

./image9.bmp

在该方法中,isAutoCloseEnabled被设置成了true

./image10.bmp

  1. 在提交transaction时,提交完成后,就会执行transactionContext.managedClose()方法,在该方法中关闭资源,包括session
  2. 注意到一个问题:

./image11.bmp

./image12.bmp

进去代理类TransactionProjectionWrapper

./image13.bmp

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值