随笔-57  评论-202  文章-17  trackbacks-0
      这一节是非常实用的一节,我在阅读此书的时候,一直在迷惑,究竟应该怎样管理Session呢?因为Session的管理是如此重要,类似于以前写程序对JDBC Connection的管理。看完此节后,终于找到了方法。
      在各种Session管理方案中,ThreadLocal模式得到了大量使用。ThreadLocal是Java中一种较为特殊的线程绑定机制。通过ThreadLocal存取的数据,总是与当前线程相关,也就是说,JVM为每个运行的线程,绑定了私有的本定实例存取空间,从而为多线程环境经常出现的并发访问问题提供了一种隔离机制。
      下面是Hibernate官方提供的一个ThreadLocal工具:


import net.sf.hibernate.
*;
import net.sf.hibernate.cfg.
*;
import org.apache.log4j.Logger;

/**
 * <p>Title: </p>
 *
 * <p>Description: Session的管理类</p>
 *
 * <p>Copyright: Copyright (c) 2005</p>
 *
 * <p>Company: </p>
 *
 * @author George Hill
 * @version 1.0
 
*/


public class HibernateUtil {

  
private static final Logger log = Logger.getLogger(HibernateUtil.class);

  
private static final SessionFactory sessionFactory;

  
/**
   * 初始化Hibernate配置
   
*/

  
static {
    
try {
      
// Create the SessionFactory
      sessionFactory = new Configuration().configure().buildSessionFactory();
    }
 catch (Throwable ex) {
      log.error(
"Initial SessionFactory creation failed.", ex);
      
throw new ExceptionInInitializerError(ex);
    }

  }


  
public static final ThreadLocal session = new ThreadLocal();

  
/**
   * 根据当前线程获取相应的Session
   * @return Session
   * @throws HibernateException
   
*/

  
public static Session currentSession() throws HibernateException {
    Session s 
= (Session) session.get();
    
// Open a new Session, if this Thread has none yet
    if (s == null{
      s 
= sessionFactory.openSession();
      session.
set(s);
    }

    
return s;
  }


  
/**
   * 返回Session给相应的线程
   * @throws HibernateException
   
*/

  
public static void closeSession() throws HibernateException {
    Session s 
= (Session) session.get();
    session.
set(null);
    
if (s != null)
      s.close();
  }


}


      针对WEB程序,还可以利用Servlet2.3的Filter机制,轻松实现线程生命周期内的Session管理。下面是一个通过Filter进行Session管理的典型案例:

public class PersistenceFilter implements Filter {
  
protected static ThreadLocal hibernateHolder = new ThreadLocal();

  
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    hibernateHolder.
set(getSession());
    
try {
      
      chain.doFilter(request, response);
      
    }
 finally {
      Session session 
= (Session) hibernateHolder.get();
      
if (session != null{
        hibernateHolder.
set(null);
        
try {
          session.close();
        }
 catch (HibernateException ex) {
          
throw new ServletException(ex);
        }

      }

    }

  }

  
}
posted on 2005-07-29 19:43 小米 阅读(3912) 评论(1)  编辑  收藏 所属分类: Hibernate

评论:
# re: 《深入浅出Hibernate》读书笔记(9)——Session管理 2005-11-06 15:07 | jiniboy
这都是你总结的吗   回复  更多评论
  

只有注册用户登录后才能发表评论。


网站导航: