【问题标题】:Externalize credentials from persistence.xml in J2SE app从 J2SE 应用程序中的 persistence.xml 外部化凭据
【发布时间】:2011-05-31 16:56:48
【问题描述】:

我正在编写一个使用 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 文件,但这有点hacky。

【问题讨论】:

    标签: hibernate jpa persistence java


    【解决方案1】:

    您可以在创建EntityManagerFactory时提供额外的属性:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-14
      • 1970-01-01
      • 1970-01-01
      • 2013-12-26
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多