在J2SE app中外化来自persistence.xml的凭据

时间:2010-12-28 18:24:50

标签: hibernate jpa persistence java

我正在编写一个使用JPA进行持久化的J2SE应用程序(没有企业容器)。这是我的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="dbstats">

    <!-- TODO: why is this needed? -->
    <class>dreambear.stats.data.GamePlayedEvent</class>
    <class>dreambear.stats.data.HyveMemberCountPoll</class>
    <class>dreambear.stats.data.ProfileCountPoll</class>
    <class>dreambear.stats.data.UserSession</class>
    <class>dreambear.stats.data.UsersOnlinePoll</class>

    <properties>

        <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
        <property name="hibernate.max_fetch_depth" value="3" />
        <property name="hibernate.hbm2ddl.auto" value="update" />

        <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />

        <!-- TODO: externalize information -->
        <property name="javax.persistence.jdbc.user" value="dbstats" />
        <property name="javax.persistence.jdbc.password" value="*****" />
        <property name="javax.persistence.jdbc.url" value="jdbc:mysql://example.com/dbstats" />

    </properties>

    </persistence-unit>

</persistence>

这是一个静态文件,“编译”到应用程序中。但是,我需要提取凭据,以便我可以在运行时从配置参数加载它们,因为它们对于例如它们是不同的。应用程序的开发和实时版本。

我以默认方式加载持久性设置:

emf = Persistence.createEntityManagerFactory("dbstats");

如何在此设置中外部化凭据?我可以在运行时生成persistence.xml文件,但这有点笨拙。

1 个答案:

答案 0 :(得分:4)

您可以在创建EntityManagerFactory时提供其他属性:

Map<String, String> properties = new HashMap<String, String>();
properties.put("javax.persistence.jdbc.user", ...);
...

emf = Persistence.createEntityManagerFactory("dbstats", properties); 
相关问题