我目前正在构建一个库来模块化我的一些代码,但我遇到了 Hibernate 的问题。
在我的主应用程序中,我有一个 hibernate 配置来获取它运行所需的信息,但我的库中也需要 hibernate ,因为我想要的一些对象可以在其他应用程序中使用。
当我启动我的 tomcat 服务器时,同时设置了两个 hibernates,我收到错误,指出 bean 无法解析,还有一个说我的查询中缺少位置参数。但是,当我仅使用应用程序 Hibernate 配置启动 Tomcat 时,它启动正常。
这是配置的样子......
来自图书馆:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<mapping resource="blah.hbm.xml"/>
<mapping resource="blargh.hbm.xml"/>
<mapping resource="stuff.hbm.xml"/>
<mapping resource="junk.hbm.xml"/>
<mapping resource="this.hbm.xml"/>
</session-factory>
</hibernate-configuration>
来自应用程序:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
<!-- Enable the query cache -->
<property name="hibernate.cache.use_query_cache">true</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">false</property>
<!-- mapping files -->
<mapping resource="appStuff"/>
<mapping resource="appBlah"/>
<mapping resource="appBlargh"/>
<mapping resource="appJunk"/>
<mapping resource="appThis"/>
</session-factory>
</hibernate-configuration>
我对 Hibernate 还是很陌生,这是一种奇怪的配置。
最佳答案
您可以以编程方式加载 hibernate 配置文件。
SessionFactory sf = new Configuration().configure("somename.cfg.xml").buildSessionFactory();
这将允许您创建两个 SessionFactory 对象。但是,我假设您想为您的应用程序和模块使用相同的 SessionFactory。
您可以将两个 hibernate XML 文件加载到一个 DOM 对象中(将您模块的“session-factory”标记子项与您的应用程序的子项组合起来),然后使用以下代码:
import org.hibernate.cfg.Configuration;
// ...
SessionFactory sf = new Configuration().configure(yourDOMObject).buildSessionFactory();
编辑:session-factory 没有被打印出来,因为它有大于和小于字符。
关于java - 多个 Hibernate 配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3449475/