假设我在这里指定了一个特定的test.hbm.xml文件。相反,我想加载我的包中可用的所有hbm.xml文件。我有很多hbm.xml映射文件。 Inastead指定每个,我想加载所有这些。怎么做?是否可以通过hibernate.cfg.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 :(得分:1)
据我所知,您将无法在XML中执行此操作(但您可能需要再次检查)
但是,您仍然可以在创建SessionFactory
对象时获得所需的结果。
这是一个以编程方式添加测试文件夹*.hbm.xml
下列出的所有com/hbmfiles
个文件的解决方案:
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。:以上代码未编译,但您肯定会得到所需的结果。
答案 1 :(得分:0)
Configuration Class中有一个方法可用于以编程方式添加目录树中存在的所有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()