日期:2014-05-17 浏览次数:20632 次
import org.hibernate.*; import org.hibernate.cfg.*; public class CoreSession { static SessionFactory sessionFactory; //注意到这里的SessionFactory都是static的 //初始化Hibernate,创建SessionFactory实例,只在该类被加载到内存时执行一次 static{ try{ Configuration config = new Configuration().configure(); sessionFactory = config.buildSessionFactory(); } catch (Exception e) { System.out.println(e.getMessage()); } } }
public class CoreSession { private static SessionFactory sessionFactory; public static SessionFactory getSessionFactory(){ if(sessionFactory == null) { try{ Configuration config = new Configuration().configure(); sessionFactory = config.buildSessionFactory(); } catch (Exception e) { e.printStackTrace(); } } return sessionFactory; } }
------解决方案--------------------
static {}静态块代码会在classloader加载这个类的时候就被执行了,所以在使用时候完全可以放心,不用担心它没有被初始化的问题!
------解决方案--------------------
package dao; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.cfg.Configuration; public class SessionFactory { private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml"; private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>(); private static Configuration configuration = new Configuration(); private static org.hibernate.SessionFactory sessionFactory; private static String configFile = CONFIG_FILE_LOCATION; static { try { configuration.configure(configFile); sessionFactory = configuration.buildSessionFactory(); } catch (Exception e) { System.err.println("%%%% Error Creating SessionFactory %%%%"); e.printStackTrace(); } } private SessionFactory() { } public static Session getSession() throws HibernateException { Session session = (Session) threadLocal.get(); if (session == null || !session.isOpen()) { if (sessionFactory == null) { rebuildSessionFactory(); } session = (sessionFactory != null) ? sessionFactory.openSession() : null; threadLocal.set(session); } return session; } public static void rebuildSessionFactory() { try { configuration.configure(configFile); sessionFactory = configuration.buildSessionFactory(); } catch (Exception e) { System.err.println("%%%% Error Creating SessionFactory %%%%"); e.printStackTrace(); } } public static void closeSession() { Session session = null; try { session = (Session) threadLocal.get(); threadLocal.set(null); if (session != n