您的位置:首页 > 其它

《深入浅出Hibernate》读书笔记(9)——Session管理

2007-04-01 22:53 281 查看
这一节是非常实用的一节,我在阅读此书的时候,一直在迷惑,究竟应该怎样管理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);


}


}


}


}








}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: