2016-02-21 82 views
0

我想製作多個hibernate.cfg.xml文件,因爲每個文件都有不同的連接屬性。我如何指定每個使用它們的類內部的哪個cfg文件?如何傳遞休眠配置參數

這裏是我的會話工廠:

public class DatabaseUtilities { 

    private static final SessionFactory sessionFactory = buildSessionFactory(); 

    private static SessionFactory buildSessionFactory(String configFile) { 
     try { 
      return new AnnotationConfiguration().configure(configFile).buildSessionFactory(); 
     } catch (Throwable ex) { 
      System.err.println("Initial SessionFactory creation failed." + ex); 
      throw new ExceptionInInitializerError(ex); 
     } 
    } 

    public static SessionFactory getSessionFactory() { 
     return sessionFactory; 
    } 

    public static void shutdown() { 
     // Close caches and connection pools 
     getSessionFactory().close(); 
    } 
} 

當然這個,因爲現在我不知道如何將參數傳遞到頂部的對象會引發錯誤。

這是我從我的課

Session s = DatabaseUtilities.getSessionFactory().openSession(); 

調用會話工廠如何修改這個代碼,以利用它的類通過在.XML的字符串?

回答

1

當你封裝訪問到一個Singleton路SessionFactory的,你也許可以改寫它不跟隨Static block initialization but Lazy initialization

public class DatabaseUtilities { 
    private static final SessionFactory sessionFactory = null; 

    private static SessionFactory buildSessionFactory(String configFile) { 
     try { 
      return new AnnotationConfiguration().configure(configFile).buildSessionFactory();   
     } catch (Throwable ex) { 
      System.err.println("Initial SessionFactory creation failed." + ex); 
      throw new ExceptionInInitializerError(ex); 
     } 
    } 

    public static synchronized SessionFactory getSessionFactory(String configFile) { 
      if (sessionFactory == null) { 
       sessionFactory = buildSessionFactory(configFile); 
      } 
      return sessionFactory; 
    } 

    public static void shutdown() { 
     // Close caches and connection pools 
     getSessionFactory().close(); 
    } 

    private DatabaseUtilities() {} 
} 

現在你可以打電話給你的公用事業類是這樣的:

DatabaseUtilities.getSessionFactory("path/to/hibernate.cfg.xml");