• Hibernate4.0之HibernateSessionFactory源码详解


    import org.hibernate.HibernateException;
    import org.hibernate.Session;
    import org.hibernate.cfg.Configuration;
    import org.hibernate.service.ServiceRegistry;
    import org.hibernate.service.ServiceRegistryBuilder;
    
    @SuppressWarnings("deprecation")
    public class HibernateSessionFactory {
    
        /** 
         * Location of hibernate.cfg.xml file.
         * Location should be on the classpath as Hibernate uses  
         * #resourceAsStream style lookup for its configuration file. 
         * The default classpath location of the hibernate config file is 
         * in the default package. Use #setConfigFile() to update 
         * the location of the configuration file for the current session.   
         */
        
        private static String CONFIG_FIEL_LOACTION = "/hibernate.cfg.xml";
        private static String configFile = CONFIG_FIEL_LOACTION;
        private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
        private static org.hibernate.SessionFactory sessionFactory;
        private static Configuration configuration = new Configuration();
        private static ServiceRegistry serviceRegistry; 

    /** 在回话工厂类HibernateSessionFactory中, 首先通过一次静态代码块来启动Hibernate,该代码块只在HibernateSessionFactory类被加载时执行一次,用于建立sessionFactory。即SessionFactory是线程安全的,只能被实例化一次。 在静态代码块中通过创建Configuration对象并调用其configure()方法读取Hibernate配置文件hibernate.cfg.xml信息,从而进行配置信息的管理。然后 创建SessionFactory实例,在Hibernate4.0版本之前,该实例创建工作由Configuration对象的buildSessionFactory()方法来完成。而Hibernater4.0版本之后,创建SessionFactory实例的方法有所改变,Hibernate 增加了一个注册ServiceRegistryBuilder类。要生成一个注册机对象,然后所有的生成 SessionFactory的对象向注册机注册一下再使用。生成方法还config.buildSessionFactory()方法,只不过加了一个注册机的参数。 */ static { try { configuration.configure(); serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry(); sessionFactory = configuration.buildSessionFactory(serviceRegistry); } catch (Exception e) { System.err.println("%%%% Error Creating SessionFactory %%%%" + e); e.printStackTrace(); } } private HibernateSessionFactory() { } /** * Returns the ThreadLocal Session instance. Lazy initialize * the <code>SessionFactory</code> if needed. * * 由于sessionFactory是线程安全的,因而同一个SessionFactory实例可以被多个线程共享,即多个并发线程可以同时访问一个SesisonFactory并 * 获得Session的实例。但由于Session不是线程安全的,如果多个并发线程同时操作同一个Session对象,就可能出现一个线程在进行数据库操作,而另一个 * 线程将Session对象关闭的情况,从而出现异常。如何才能保证线程安全呢?这就要求SessionFactory能够针对不同的线程创建不同的Session对象,即 * 需要对Session进行有效的管理,Hibernate中使用ThreadLocal对象来维护和管理Session实例。 * * ThreadLocal是线程局部变量,线程局部变量高效的为每一个使用它的线程提供单独的线程局部变量的副本。为了实现为每个线程维护一个变量的副本,ThreadLocal * 类提供了一个Map结构,是key值用来保存线程的ID, value用来保存一个Session实例的副本。这样多线程并发操作时,实在与自己绑定的Session实例副本上进行 * 的,从而避免多个线程横在同一个Session实例上操作是可能导致的数据异常。 * * 在HibernaterSessionFctory类的getSession()方法中,首先调用ThreadLocal类的get()方法获得当前线程的Session对象,然后判断当前线程是否已存在 * Session对象或者对象未打开,在判断SessionFactory对象是否为空,如果SeesionFctory对象不存在,先调用rebuildSessionFactory()方法创建SesionFactory, * 如果SessionFactory对象已经存在,则调用SessionFactory对象的openSession()方法创建Session对象。创建完Session对象后,还需要调用ThreadLocal的set() * 方法为该线程保存Session对象。 * * @return Session * @throws HibernateException */ public static Session getSession() { Session session = (Session) threadLocal.get(); try{ if (session == null || !session.isOpen()) { if (sessionFactory == null) { rebuildSessionFactory(); } session = (sessionFactory != null) ? sessionFactory.openSession() : null; threadLocal.set(session); } } catch (HibernateException e){ System.err.println("%%%% Error Creating getSession %%%%" + e); e.printStackTrace(); } return session; } /** * Rebuild hibernate session factory * */ public static void rebuildSessionFactory() { synchronized(sessionFactory){ try { configuration.configure(configFile); serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry(); sessionFactory = configuration.buildSessionFactory(serviceRegistry); } catch (Exception e) { System.err.println("%%%% Error rebuildSessionFactory %%%%" + e); e.printStackTrace(); } } } /** * Close the single hibernate session instance. * * @throws HibernateException */ public static void closeSession(){ Session session = (Session) threadLocal.get(); threadLocal.set(null); try{ if (session != null && session.isOpen()) { session.close(); } } catch(HibernateException e){ System.err.println("%%%% Error closeSession %%%%" + e); e.printStackTrace(); } } /** * return session factory * */ public static org.hibernate.SessionFactory getSessionFactory() { return sessionFactory; } /** * return hibernate configuration * */ public static Configuration getConfiguration() { return configuration; } public static void setConfigFile(String configFile){ HibernateSessionFactory.configFile = configFile; } }
  • 相关阅读:
    MySQL中的数据类型
    Java中的List集合和迭代器
    关系数据库(MySQL)的规范化、以及设计原则
    了解数据模型、以及MySQL使用的数据模型
    Python中的基本语法
    c++、Java、python对应的编译型语言和解释性语言区别详解
    从码云克隆一个项目
    使用码云来添加远程仓库
    删除Git管理的文件
    LocalDateTime
  • 原文地址:https://www.cnblogs.com/hujunzheng/p/4619460.html
Copyright © 2020-2023  润新知