zoukankan      html  css  js  c++  java
  • Hibernate3回顾-3-Session管理

    3.Session管理

    仅为个人理解.请指正

    3.1背景

    由于Configuration的创建耗费系统的资源。所以有必要只将Configuration实例化一次,之后通过SessionFactory获取session会话。一般都会手动封装一个HibernateUtil类(未使用Spring管理的前提下). 该类的作用使Hibernate加载配置文件config, 创建sessionFactory等只运行一次. 如下代码:

     1 public class HibernateUtil {
     2     private static final SessionFactory sessionFactory = buildSessionFactory();
     3     private static SessionFactory buildSessionFactory() {
     4         try {
     5             // Create the SessionFactory from hibernate.cfg.xml
     6             return new Configuration().configure().buildSessionFactory();
     7         } catch (Throwable ex) {
     8             // Make sure you log the exception, as it might be swallowed
     9             System.err.println("Initial SessionFactory creation failed." + ex);
    10             throw new ExceptionInInitializerError(ex);
    11         }
    12     }
    13     public static SessionFactory getSessionFactory() {
    14         return sessionFactory; 
    15     }
    16 }

    在静态方法中实例化,获取sessionFactory的实例。然后通过getSessionFactory().getOpenSession();

    获取session。

    类似的,之前有一种相对原始简单的进一步封装方式。如下:可见这种简单的封装进一步把增删改查等需求打包。

      1 package com.test.util;
      2 
      3 import java.io.Serializable;
      4 import org.hibernate.Session;
      5 import org.hibernate.SessionFactory;
      6 import org.hibernate.Transaction;
      7 import org.hibernate.cfg.Configuration;
      8 
      9 /** 
     10  * 工具类网络优化版
     11  */
     12 public  final class HibernateUtil2 {    //final类不允许被继承  {
     13      private static SessionFactory sessionFactory;  //私有静态属性
     14      private static ThreadLocal session = new ThreadLocal();
     15 
     16      private HibernateUtil2() {      //私有的构造方法 禁止实例化
     17      }
     18 
     19      static {                       //static块只会在虚拟机进行加载时被执行一次
     20       Configuration cfg = new Configuration();
     21       cfg.configure();       //读取配置文件信息,默认配置文件是"hibernate.cfg.xml"
     22       sessionFactory = cfg.buildSessionFactory();
     23      }
     24 
     25      public static Session getThreadLocalSession() {
     26       Session s = (Session) session.get();
     27       if (s == null) {
     28        s = getSession();
     29        session.set(s);
     30       }
     31       return s;
     32      }
     33 
     34      public static void closeSession() {
     35       Session s = (Session) session.get();
     36       if (s != null) {
     37        s.close();
     38        session.set(null);
     39       }
     40      }
     41 
     42      public static SessionFactory getSessionFactory() {
     43       return sessionFactory;
     44      }
     45 
     46      public static Session getSession() {
     47       return sessionFactory.openSession();
     48      }
     49             //数据库操作:增
     50      public static void add(Object entity) {
     51       Session s = null;
     52       Transaction tx = null;
     53       try {
     54        s = HibernateUtil2.getSession();
     55        tx = s.beginTransaction();
     56        s.save(entity);
     57        tx.commit();
     58       } finally {                  //确保Session被关闭
     59        if (s != null)
     60         s.close();
     61       }
     62      }
     63             //数据库操作:改
     64      public static void update(Object entity) {
     65       Session s = null;
     66       Transaction tx = null;
     67       try {
     68        s = HibernateUtil2.getSession();
     69        tx = s.beginTransaction();
     70        s.update(entity);
     71        tx.commit();
     72       } finally {
     73        if (s != null)
     74         s.close();
     75       }
     76      }
     77             //数据库操作:删
     78      public static void delete(Object entity) {
     79       Session s = null;
     80       Transaction tx = null;
     81       try {
     82        s = HibernateUtil2.getSession();
     83        tx = s.beginTransaction();
     84        s.delete(entity);
     85        tx.commit();
     86       } finally {
     87        if (s != null)
     88         s.close();
     89       }
     90      }
     91             //数据库操作:查询    通过主键id查询数据库中一个表的一行信息。Class 对应数据库表 或者 domain中的实体对象类,Serializable 序列号
     92      public static Object get(Class clazz, Serializable id) {
     93       Session s = null;
     94       try {
     95        s = HibernateUtil2.getSession();
     96        Object obj = s.get(clazz, id);
     97        return obj;
     98       } finally {
     99        if (s != null)
    100         s.close();
    101       }
    102      }
    103     }


    3.2 使用ThreadLocal管理session

    总而言之:在HibernateUtil类中封装hibernate的管理.通过openSession取得 session,并将其放入ThreadLocal变量中. 这样业务逻辑中仅需通过工具类取得当前线程对应的session.使用完毕后,将 session关闭,将当前线程的ThreadLocal变量置为NULL. 保证线程归还线程池复用后,ThreadLocal为空,以免出现导致其他线程访问到本线程变量.

    详细:

    Session是由SessionFactory负责创建的,而SessionFactory的实现是线程安全的,多个并发的线程可以同时访问一个SessionFactory并从中获取Session实例,那么Session是否是线程安全的呢?很遗憾,答案是否定的。Session中包含了数据库操作相关的状态信息,那么说如果多个线程同时使用一个Session实例进行CRUD,就很有可能导致数据存取的混乱,你能够想像那些你根本不能预测执行顺序的线程对你的一条记录进行操作的情形吗?       在Session的众多管理方案中,我们今天来认识一种名为ThreadLocal模式的解决方案。ThreadLocal并非是一个线程的本地实现版本,它并不是一个Thread,而是thread local variable(线程局部变量)也许把它命名为ThreadLocalVar更加合适。线程局部变量(ThreadLocal)其实的功用非常简单,就是为每一个使用该变量的线程都提供一个变量值的副本,是每一个线程都可以独立地改变自己的副本,而不会和其它线程的副本冲突。从线程的角度看,就好像每一个线程都完全拥有一个该变量。

    那麽具体如何利用ThreadLocal来管理Session呢?Hibernate官方文档手册的示例之中,提供了一个通过ThreadLocal维护Session的好榜样:

     1 package com.test.util;
     2 
     3 import org.hibernate.HibernateException;
     4 import org.hibernate.Session;
     5 import org.hibernate.SessionFactory;
     6 import org.hibernate.cfg.Configuration;
     7 
     8 public class HibernateUtil_Thread {
     9     public static final SessionFactory sessionFactory;
    10     static {
    11         try {
    12             sessionFactory = new Configuration().configure().buildSessionFactory();
    13         } catch (Throwable ex) {
    14             throw new ExceptionInInitializerError(ex);
    15         }
    16     }
    17     public static final ThreadLocal<Session> session = new ThreadLocal<Session>();
    18 
    19     public static Session currentSession() throws HibernateException {
    20         Session s = session.get();
    21         if (s == null) {
    22             s = sessionFactory.openSession();
    23             session.set(s);
    24         }
    25         return s;
    26     }
    27 
    28     public static void closeSession() throws HibernateException {
    29         Session s = session.get();
    30         if (s != null) {
    31             s.close();
    32         }
    33         session.set(null);
    34     }
    35 }

    使用eclipse工具也会生成类似上面的代码。如下:

      1 package com.test.db;
      2 
      3 import org.hibernate.HibernateException;
      4 import org.hibernate.Session;
      5 import org.hibernate.cfg.Configuration;
      6 import org.hibernate.cfg.AnnotationConfiguration;
      7 /**
      8  * Configures and provides access to Hibernate sessions, tied to the
      9  * current thread of execution.  Follows the Thread Local Session
     10  * pattern, see {@link http://hibernate.org/42.html }.
     11  */
     12 public class HibernateSessionFactory {
     13 
     14     /** 
     15      * Location of hibernate.cfg.xml file.
     16      * Location should be on the classpath as Hibernate uses  
     17      * #resourceAsStream style lookup for its configuration file. 
     18      * The default classpath location of the hibernate config file is 
     19      * in the default package. Use #setConfigFile() to update 
     20      * the location of the configuration file for the current session.   
     21      */
     22     private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
     23     private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
     24     private  static Configuration configuration = new AnnotationConfiguration();    
     25     private static org.hibernate.SessionFactory sessionFactory;
     26     private static String configFile = CONFIG_FILE_LOCATION;
     27 
     28     static {
     29         try {
     30             configuration.configure(configFile);
     31             sessionFactory = configuration.buildSessionFactory();
     32         } catch (Exception e) {
     33             System.err
     34                     .println("%%%% Error Creating SessionFactory %%%%");
     35             e.printStackTrace();
     36         }
     37     }
     38     private HibernateSessionFactory() {
     39     }
     40     
     41     /**
     42      * Returns the ThreadLocal Session instance.  Lazy initialize
     43      * the <code>SessionFactory</code> if needed.
     44      *
     45      *  @return Session
     46      *  @throws HibernateException
     47      */
     48     public static Session getSession() throws HibernateException {
     49         Session session = (Session) threadLocal.get();
     50 
     51         if (session == null || !session.isOpen()) {
     52             if (sessionFactory == null) {
     53                 rebuildSessionFactory();
     54             }
     55             session = (sessionFactory != null) ? sessionFactory.openSession()
     56                     : null;
     57             threadLocal.set(session);
     58         }
     59 
     60         return session;
     61     }
     62 
     63     /**
     64      *  Rebuild hibernate session factory
     65      *
     66      */
     67     public static void rebuildSessionFactory() {
     68         try {
     69             configuration.configure(configFile);
     70             sessionFactory = configuration.buildSessionFactory();
     71         } catch (Exception e) {
     72             System.err
     73                     .println("%%%% Error Creating SessionFactory %%%%");
     74             e.printStackTrace();
     75         }
     76     }
     77 
     78     /**
     79      *  Close the single hibernate session instance.
     80      *
     81      *  @throws HibernateException
     82      */
     83     public static void closeSession() throws HibernateException {
     84         Session session = (Session) threadLocal.get();
     85         threadLocal.set(null);
     86 
     87         if (session != null) {
     88             session.close();
     89         }
     90     }
     91 
     92     /**
     93      *  return session factory
     94      *
     95      */
     96     public static org.hibernate.SessionFactory getSessionFactory() {
     97         return sessionFactory;
     98     }
     99 
    100     /**
    101      *  return session factory
    102      *
    103      *    session factory will be rebuilded in the next call
    104      */
    105     public static void setConfigFile(String configFile) {
    106         HibernateSessionFactory.configFile = configFile;
    107         sessionFactory = null;
    108     }
    109 
    110     /**
    111      *  return hibernate configuration
    112      *
    113      */
    114     public static Configuration getConfiguration() {
    115         return configuration;
    116     }
    117 }

    3.3 新的解决方案:getCurrentSession

    总而言之:Hibernate的SessionFactory提供获取session的新方法getCurrentSession (获得与当前线程绑定的session). 内部通过代理封装,此方式得到的session 不仅和当前线程绑定,也无需手动开关. 默认在事务提交之后,session自动关闭. 此外hibernate.cfg.xml配置文件中也需配置

    <property name="current_session_context_class">thread</property> 基于线程
     
    题外话引入Spring之后.sessionfactory的创建等都交给spring管理.Spring也提供了HibernateTemplate,HibernateDaoSupport这样的封装方法. 用户可以不再考虑session的管理,事务的开启关闭.只需配置事务即可. 而所谓session关闭后,因延迟加载导致前台无法显示的问题以往解决方式为强制全部加载,现在也可通过在web.xml中配置
    org.springframework.orm.hibernate3.support.OpenSessionInViewFilter来解决.
     
    详细描述

    使用 Hibernate 的大多数应用程序需要某种形式的“上下文相关的”会话,特定的会话在整个特定的上下文范围内始终有效。然后不同应用程序中对“上下文”一词的定义和理解是不同的。

    在Hibernate3.0之前,使用Hibernate的程序要么自行编写基于ThreadLocal的上下文会话,要么采用HibernateUtil这样的辅助类,要么使用第三方框架(如spring或pico),他们提供了基于代理或者基于拦截器的上下文相关会话。

    Hibernate 3.1之后,Hibernate增加了SessionFactory.getCurrentSession()方法。该方法实现是可拔插的(通过org.hibernate.context.CurrentSessionContext)和新的配置参数

    (hibernate.current_session_context_class),以便对什么是当前会话的范围(scope)和上下文(context)的定义进行拔插。

    请参阅 org.hibernate.context.CurrentSessionContext接口的 Javadoc,那里有关于它的契约的详

    细讨论。它定义了单一的方法,currentSession(),特定的实现用它来负责跟踪当前的上下文相关

    的会话。Hibernate 内置了此接口的三种实现:

    org.hibernate.context.JTASessionContext当前会话根据  JTA 来跟踪和界定。这和以前的仅支

    JTA 的方法是完全一样的。详情请参阅 Javadoc

    org.hibernate.context.ThreadLocalSessionContext当前会话通过当前执行的线程来跟踪和界

    。详情也请参阅 Javadoc

    org.hibernate.context.ManagedSessionContext:当前会话通过当前执行的线程来跟踪和界定。但

    是,你需要负责使用这个类的静态方法将  Session 实例绑定、或者取消绑定,它并不会打开

    open)、flush 或者关闭(close)任何 Session

    这两种实现都提供了“每数据库事务对应一个session”的编程模型,也称作每次请求对应一个session。Hibernate session的起始和终结由数据库事务的生存来控制。假若你采用自行编写代码来管理事务(比如,在纯粹的J2SE,或者JTA/UserTransaction/BMT),建议你使用Hibernate Transaction API来把底层事务实现从你的代码中隐藏掉。如果你在支持CMT的EJB容器中执行,事务边界是声明式定义的,你不需要在代码中进行任何事务或session管理操作。请参阅第 11 章 事务和并发一节来阅读更多的内容和示例代码。

    hibernate.current_session_context_class 配置参数定义了应该采用哪个org.hibernate.context.CurrentSessionContext实现。注意,为了向下兼容,如果未配置此参数,但是存在org.hibernate.transaction.TransactionManagerLookup的配置,Hibernate会采用org.hibernate.context.JTASessionContext。一般而言,此参数的值指明了要使用的实现类的全名,但那两个内置的实现可以使用简写,"jta""thread"。      

     

    常见混淆

    1 getCurrentSession创建的session会和绑定到当前线程,而openSession不会。

    2 getCurrentSession创建的线程会在事务回滚或事物提交后自动关闭,而openSession必须手动关闭

    这里getCurrentSession本地事务(本地事务:jdbc)时 要在配置文件里进行如下设置

     * 如果使用的是本地事务(jdbc事务)  <property name="hibernate.current_session_context_class">thread</property>  * 如果使用的是全局事务(jta事务)  <property name="hibernate.current_session_context_class">jta</property>

    getCurrentSession () 使用当前的session openSession()         重新建立一个新的session

    在一个应用程序中,如果DAO 层使用Spring 的hibernate 模板,通过Spring 来控制session 的生命周期,则首选getCurrentSession ()。

     
     
  • 相关阅读:
    Jzoj4822 完美标号
    Jzoj4822 完美标号
    Jzoj4792 整除
    Jzoj4792 整除
    Educational Codeforces Round 79 A. New Year Garland
    Good Bye 2019 C. Make Good
    ?Good Bye 2019 B. Interesting Subarray
    Good Bye 2019 A. Card Game
    力扣算法题—088扰乱字符串【二叉树】
    力扣算法题—086分隔链表
  • 原文地址:https://www.cnblogs.com/redcoatjk/p/3630889.html
Copyright © 2011-2022 走看看