我正在编写一个使用 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 文件,但这有点麻烦。
您可以在创建时提供附加属性EntityManagerFactory
:
Map<String, String> properties = new HashMap<String, String>();
properties.put("javax.persistence.jdbc.user", ...);
...
emf = Persistence.createEntityManagerFactory("dbstats", properties);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)