多个Hibernate配置

问题描述 投票:8回答:2

我正在构建一个库来模块化我的一些代码,我遇到了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的新手,这是一种奇怪的配置。

java hibernate
2个回答
12
投票

您可以以编程方式加载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();

编辑:未打印会话工厂,因为它具有大于和小于字符。


2
投票

如果你想正确使用hibernate shard qazxsw poi。否则,您只需传递要使用的hibernate.cfg.xml的路径(在文件系统或类路径中)

来自图书馆

1

从应用程序:

SessionFactory sf = new Configuration()
    .configure("Fromthelibrary.cfg.xml")
    .buildSessionFactory();
© www.soinside.com 2019 - 2024. All rights reserved.