转自
将一些常用的方法录入自己的工具类中,在使用时直接调用工具类里的方法,给我们编写程序带来了极大的方便,既使得程序简洁直观、便于维护,又很好的做到了代码复用。
这里,在学习Hibernate的过程中,将工具类整理如下,三个版本逐渐提升,参考如下:
Version 1.0
package com.zhangsx.utils;
import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration;
public class HbnUtil1 { private static SessionFactory sf; static { try { sf = new Configuration().configure().buildSessionFactory(); } catch (HibernateException e) { e.printStackTrace(); } } public static Session getSession() { Session s = null; if(sf != null && !sf.isClosed()) { s = sf.openSession(); } return s; } public static void releaseSession(Session s) { if(s != null && s.isOpen()) s.close(); } public static void cleanSessionFactory(SessionFactory sf) { if(sf != null && !sf.isClosed()) sf.close(); } }
Version 2.0 * 这里使用ThreadLocal来管理Hibernate Session,使得一个线程维护一个Session,实现了线程范围内
的Session共享。 * 使用时将不安全的对象封装进ThreadLocal。
* ThreadLocal提供了线程安全的共享对象,它通过为每一个线程提供一个独立的变量副本来解决变量并
发访问的冲突问题,实现多线程的并发访问。
*关于ThreadLocal的详解,请参见 http://blog.sina.com.cn/s/blog_5cee63250100b0mb.html
package com.zhangsx.utils;
import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration;
public class HbnUtil2 { private static SessionFactory sf; private static ThreadLocal local = new ThreadLocal(); static { try { sf = new Configuration().configure().buildSessionFactory(); } catch (HibernateException e) { e.printStackTrace(); } }
public static Session getSession() { Session s = (Session) local.get(); if (s == null && sf != null && !sf.isClosed()) { s = sf.openSession(); local.set(s); } return s; }
public static void releaseSession(Session s) { if (s != null && s.isOpen()) { s.close(); } local.set(null); }
}
Version 3.0
* 使用getCurrentSession()方法来管理Hibernate Session,该方法总是返回“当前的”工作单元。
* Session在第一次被使用的时候,即第一次调用getCurrentSession()的时候,其生命周期就开始。然
后她被Hibernate绑定到当前线程。当事务结束的时候,不管是提交还是回滚,Hibernate会自动把
Session从当前线程剥离,并且关闭。若在次调用getCurrentSession(),会得到一个新的Session,并
且开始一个新的工作单元。这是Hibernate最广泛的thread-bound model,支持代码灵活分层(事务划
分和数据访问代码的分离)。
package com.zhangsx.utils;
import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration;
public class HbnUtil3 { private static SessionFactory sf; static { try { sf = new Configuration().configure().buildSessionFactory(); } catch (HibernateException e) { e.printStackTrace(); } }
public static Session getCurrentSession() { if (sf == null) return null; return sf.getCurrentSession(); }
public static void clearSessionFactory() { if (sf != null && !sf.isClosed()) sf.close(); }
}