hibernate初始化

static {
        try {
            // Create the SessionFactory
            sessionFactory = new Configuration().configure()
                    .buildSessionFactory();
        } catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            log.error("Initial SessionFactory creation failed.", ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

以上是HibernateUtil.java的初始化hibernate的代碼

主要是讓hibernate去解析相關的xml文件;準備向外提供服務

hibernate工作的最小的單位是session;所以你看那些方法裏首先都需要得到一個session;如
public static void add(Object obj) {
        if (obj == null) {
            return;
        }

        Session s = currentSession();
        Transaction tx = s.beginTransaction();
        s.save(obj);
        tx.commit();
    }

session會去生成sql並去操作數據庫

其中Session s = currentSession();就是獲取session;你可以進一步看看currentSession()的代碼:

    public static Session currentSession() {
        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就會讓sessionFactory.openSession();有的話就獲取當前的session;Session s = (Session) session.get();

啓動tomcat的時候靜態化的代碼會被執行;這個過程是自動的;不需要程序員調用

static {
        try {
            // Create the SessionFactory
            sessionFactory = new Configuration().configure()
                    .buildSessionFactory();
        } catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            log.error("Initial SessionFactory creation failed.", ex);
            throw new ExceptionInInitializerError(ex);
        }
    }


這是一個靜態的初始化器;jp裏學過的;在jvm進程啓動的時候執行且執行一次


注意HibernateUtil.java中有2種session:
1: (java.lang.)ThreadLocal    session
2: (org.hibernate.)Session      s

s纔是hibernate裏面的處理和數據庫交互的session;你可以仔細研究下里面的各種方法

1: (java.lang.)ThreadLocal    session 是ThreadLocal這個類的一個對象;是每一個具體線程的本地變量容器。觸發的每一個action都會在tomcat啓動一個線程;每一個線程在運行過程中自己使用的相關數據,對象,等等都可以存在它的ThreadLocal對象中。 每個線程都有自己的ThreadLocal對象,即session。

如某個action觸發的線程會操作數據庫,那麼它會調用hibernate的s來做;這時 session(見1)裏會存有s(見2)的。

因此:    public static Session currentSession() {

    Session s = (Session) session.get();//如果當前線程如果還活着, 就會通過這句話獲得hibernate的Session s;

如果當前線程的ThreadLocal(session)裏取出的Hibernate Session(s)是空;說明這個action是第一次來操作數據庫,於是從初始化好的SessionFactory裏拿一個

        if (s == null) {
            s = sessionFactory.openSession();
            session.set(s);
        }
        return s;

以上就是hibernate裏開始過程
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章