import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateUtil { PRivate static SessionFactory sessionFactory = null; static { try { Configuration cfg = new Configuration().configure(); sessionFactory = cfg.buildSessionFactory(); } catch (HibernateException e) { // TODO: handle exception e.printStackTrace(); } } public static SessionFactory getSessionFactory() { return sessionFactory; } public static Session getSession() { Session session = (sessionFactory != null) ? sessionFactory.openSession() : null; return session; } public static void closeFactory(Session session) { if (session != null) { if (session.isOpen()) { session.close(); } } } } 1.這個工具類可以直接使用獲取session(static方法) 但是需要注意的是這個類不是線程安全的 hibernate提倡用線程安全的工具類
2.具體過程可以理解為得到Configuration對象--->得到session工廠 sessionFactory--->獲得session openSession();最終調用session的各種方法進行數據操作。
3.可以參考hibernate文檔 有非常詳細的介紹 hibernate-distribution-3.3.2.GA/documentation/manual/zh-CN 中文版在document文件夾下
文檔內容
1.1.6.啟動和輔助類It is time to load and store someEventobjects, but first you have to complete the setup with some infrastructure code. You have to startup Hibernate by building a globalorg.hibernate.SessionFactoryobject and storing it somewhere for easy access in application code. Aorg.hibernate.SessionFactoryis used to obtainorg.hibernate.Sessioninstances. Aorg.hibernate.Sessionrepresents a single-threaded unit of work. Theorg.hibernate.SessionFactoryis a thread-safe global object that is instantiated once.
We will create aHibernateUtilhelper class that takes care of startup and makes accessing theorg.hibernate.SessionFactorymore convenient.
package org.hibernate.tutorial.util; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateUtil { private static final SessionFactory sessionFactory = buildSessionFactory(); private static SessionFactory buildSessionFactory() { try { // Create the SessionFactory from hibernate.cfg.xml return new Configuration().configure().buildSessionFactory(); } catch (Throwable ex) { // Make sure you log the exception, as it might be swallowed System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { return sessionFactory; } } 新聞熱點
疑難解答