Java-Hibernate可以在persistence.xml中的两个数据库配置之间进行选择吗?

问题描述 投票:0回答:1

我有一个在Tomcat 7.0上运行的Java应用程序,并且Hibernate管理数据库。

我需要能够根据系统环境变量(或其他可能的排序标志)来切换jdbc.url。最终,我希望能够部署指向两个不同数据库的Web应用程序的stagingproduction版本。但是,此刻,我必须在jdbc.url中物理更改persistence.xml值,并在配置之间进行切换时重新保存它。]

我当前的persistence.xml文件是:

<persistence xmlns="http://java.sun.com/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
             version="2.0">

    <persistence-unit name="my_pu" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <shared-cache-mode>ALL</shared-cache-mode>
        <properties>
            <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
            <property name="javax.persistence.jdbc.url" value="jdbc:mysql://my.rds.url.goes.here/mydatabase" />
            <property name="javax.persistence.jdbc.user" value="myusername" />
            <property name="javax.persistence.jdbc.password" value="mypassword" />
            <property name="connection.provider_class" value="org.hibernate.connection.C3P0ConnectionProvider"/>
        </properties>
    </persistence-unit>

</persistence>

我已经读过有关使用createEntityManagerFactory()作为选项的信息,但是我找不到如何实现此功能的任何清晰示例。我敢肯定这个问题已经解决过,但是我找不到干净的教程或建议。

我如何拥有我的Hibernate交换机数据库配置,而不必每次都重写persistence.xml文件?

我有一个在Tomcat 7.0上运行的Java应用程序,其中Hibernate管理数据库。我需要能够根据系统环境变量(或可能的其他排序标志)切换jdbc.url。 ...

java hibernate tomcat persistence
1个回答
0
投票

几种方法,如果您在项目中使用spring或maven,可能是:

© www.soinside.com 2019 - 2024. All rights reserved.