Hibernate4获取sessionFactory

  /** 
     * 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_FILE_LOCATION = "/hibernate.cfg.xml";
  private  static Configuration configuration = new AnnotationConfiguration();    
    private static SessionFactory sessionFactory;
    private static ServiceRegistry serviceRegistry;
    private static String configFile = CONFIG_FILE_LOCATION;

    static {
        try {
            /*
             * Hibernate4.3 已经放弃用该方式注册sessionFactory,
             * 可以用如下方式获取。
             */
            configuration.configure(configFile);  
            serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build(); 
            sessionFactory = configuration.buildSessionFactory(serviceRegistry);
            
        } catch (Exception e) {
            System.err.println("##############################Error Creating SessionFactory##############################");
            e.printStackTrace();
        }
    }
private HibernateSessionFactory() { } /** * Returns the ThreadLocal Session instance. Lazy initialize * the <code>SessionFactory</code> if needed. * * @return Session * @throws HibernateException */  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; }

 

posted @ 2017-04-11 17:43  wxw_wang  阅读(784)  评论(0编辑  收藏  举报
/* 下雪 begin */ /* 下雪 end */ /* 点击出现爱心特效 begin*/ /* 点击出现爱心特效 end*/