2016-02-03 14 views
1

假設在這裏我指定了一個特定的test.hbm.xml文件。相反,我想加載我的包中可用的所有hbm.xml文件。我有很多hbm.xml映射文件。 Inastead指定他們每個人,我想加載所有的人。怎麼做?是否有可能通過hibernate.cfg.xml文件加載它們?如何在hibernate中加載hibernate.cfg.xml中的所有xml映射文件?

hibernate-configuration> 
    <session-factory> 
     <property name="hibernate.bytecode.use_reflection_optimizer">false</property> 
     <property name="hibernate.connection.driver_class">org.h2.Driver</property> 
     <property name="hibernate.connection.password"></property> 
     <property name="hibernate.connection.url">jdbc:h2:mem:dbUnitTest;DB_CLOSE_DELAY=-1;INIT=CREATE SCHEMA IF NOT EXISTS SFMFG\;SET SCHEMA SFMFG</property> 
     <property name="hibernate.connection.username">sa</property> 
     <property name="hibernate.dialect">org.hibernate.dialect.H2Dialect</property> 
     <property name="cache.provider_class">org.hibernate.cache.EhCacheProvider</property> 
     <property name="hibernate.cache.use_second_level_cache">true</property> 

     <mapping resource="test.hbm.xml"/> 
    </session-factory> 
</hibernate-configuration> 

回答

0

配置類中有一種方法可用於以編程方式添加目錄樹中存在的所有hbm.xml文件。

 /** 
    * Read all mapping documents from a directory tree. 
    * <p/> 
    * Assumes that any file named <tt>*.hbm.xml</tt> is a mapping document. 
    * 
    * @param dir The directory 
    * @return this (for method chaining purposes) 
    * @throws MappingException Indicates problems reading the jar file or 
    * processing the contained mapping documents. 
    */ 
    public Configuration addDirectory(File dir) throws MappingException { 
     metadataSources.addDirectory(dir); 
     return this; 
    } 

您可以使用此方法獲取SessionFactory的

SessionFactory sessionFactory = new Configuration().addDirectory(new File("")).configure().buildSessionFactory() 
1

據我所知,你將不能夠做到這一點的XML(但您可能想再次在該檢查)

但儘管如此,你可以在創建得到期望的結果您的SessionFactory對象。

這是一個解決方案,以增加測試文件夾com/hbmfiles編程中列出的所有*.hbm.xml文件:

private static SessionFactory buildSessionFactory() { 
    try { 
     Configuration configuration = new Configuration(); 

     configuration.configure("/com/persistence/hibernate.cfg.xml"); 

     File[] files = new File("com/hbmfiles").listFiles(); 

     for(File file : files) { 
      if(file.toString().endsWith("hbm.xml")) 
       configuration.addResource(file); 
     } 

     SessionFactory sessionFactory = configuration.buildSessionFactory(); 

     return sessionFactory; 

    } catch (Throwable ex) { 
     System.err.println("Initial SessionFactory creation failed." + ex); 
     throw new ExceptionInInitializerError(ex); 
    } 
} 

N.B:上面的代碼不編譯,但你會得到期望的結果是肯定的。

相關問題