普通的旧Java应用程序,没有附加Web服务器(甚至不是JBoss),正在使用JPA来查询数据库。
JDBC密码在persistence.xml
:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="PU" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:postgresql:DATABASE"/>
<property name="javax.persistence.jdbc.user" value="USERNAME"/>
<property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver"/>
<property name="javax.persistence.jdbc.password" value="PASSWORD"/>
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/>
<property name="hibernate.hbm2ddl.auto" value="validate"/>
</properties>
</persistence-unit>
</persistence>
可以实例化JNDI subcontext以在应用程序的main
方法中设置密码。这可能允许使用JTA数据源:
<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="PU" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:/DefaultDS</jta-data-source>
<properties>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
</properties>
</persistence-unit>
</persistence>
您如何将密码外部化,使其在persistence.xml
内不再存在?
注意:persistence.xml
存储在公共存储库中,因此如果密码没有尖叫,那就太好了,请破解我。相反,JDBC连接信息应该放在一个不会被检入存储库的文件中。
答案 0 :(得分:2)
在实例化overriding时,EntityManagerFactory
属性可以将密码外部化:
private EntityManagerFactory getEntityManagerFactory() {
return Persistence.createEntityManagerFactory( getPersistenceUnitName(),
getProperties() );
}
private Map getProperties() {
Map result = new HashMap();
// Read the properties from a file instead of hard-coding it here.
// Or pass the password in from the command-line.
result.put( "javax.persistence.jdbc.password", "PASSWORD" );
return result;
}