理解hibernate 已ThreadLocal管理session的机制。

本文介绍了Hibernate框架中如何通过SessionFactory获取Session,并详细解析了使用ThreadLocalSessionContext实现的线程绑定机制,确保每个线程拥有独立的Session实例。

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

在运用中我们获得sesion 以

  Session session = sessionFactory.getCurrentSession();

在这里如果我们采用thread方法对事务进行管理,即采用jdbc事务,那么sessionFactory的底层是通过ThreadLocalSessionContext类来获得session对象代码如下:

 public org.hibernate.classic.Session getCurrentSession() throws HibernateException {
  if ( currentSessionContext == null ) {
   throw new HibernateException( "No CurrentSessionContext configured!" );
  }
  return currentSessionContext.currentSession();
 }

其中currentSessionContext类型为ThreadLocalSessionContext

在ThreadLocalSessionContext的currentSession我们可见:

 public final Session currentSession() throws HibernateException {
  Session current = existingSession( factory );
  if (current == null) {
   current = buildOrObtainSession();
   // register a cleanup synch
   current.getTransaction().registerSynchronization( buildCleanupSynch() );
   // wrap the session in the transaction-protection proxy
   if ( needsWrapping( current ) ) {
    current = wrap( current );
   }
   // then bind it
   doBind( current, factory );//把当前的session和sessionFactory与当前线程关联
  }
  return current;
 }

 

doBind()方法实现如下:

protected static Map sessionMap() {
  return ( Map ) context.get();
 }

 private static void doBind(org.hibernate.Session session, SessionFactory factory) {
  Map sessionMap = sessionMap();//sessionMap方法为获得与当前线程绑定的值,返回为Map类型
  if ( sessionMap == null ) {
   sessionMap = new HashMap();
   context.set( sessionMap );
  }
  sessionMap.put( factory, session );//把factory和session放入与当前线程绑定的map中,这样,就形成了当前线程与session的传递关联。
 }

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值