Hibernate有很多值得学习的地方,这里我们主要介绍Hibernate ThreadLocal,包括介绍Hibernate官方开发手册标准示例等方面。
Hibernate ThreadLocal
它会为每个线程维护一个私有的变量空间。实际上, 其实现原理是在JVM 中维护一个Map,这个Map的key 就是当前的线程对象,而value则是 线程通过Hibernate ThreadLocal.set方法保存的对象实例。当线程调用Hibernate ThreadLocal.get方法时, Hibernate ThreadLocal会根据当前线程对象的引用,取出Map中对应的对象返回。
这样,Hibernate ThreadLocal通过以各个线程对象的引用作为区分,从而将不同线程的变量隔离开来。
Hibernate官方开发手册标准示例:
- public class HibernateUtil {
- private static SessionFactory sessionFactory;
- static {
- try {
- // Create the SessionFactory sessionFactory = new Configuration().
configure().buildSessionFactory();- }
- catch (HibernateException ex) {
- throw new RuntimeException( "Configuration problem: " + ex.getMessage(), ex );
- }
- }
- public static final ThreadLocal session = new ThreadLocal();
- 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;
- }
- public static void closeSession() throws HibernateException {
- Session s = (Session) session.get();
- session.set(null);
- if (s != null) s.close();
- }
- }
通过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 sess = (Session)hibernateHolder.get();
- if (sess != null) { hibernateHolder.set(null);
- try { sess.close(); } catch (HibernateException ex) {
- throw new ServletException(ex);
- }
- }
- }
- }
- ……
- }
【编辑推荐】