所以我有一个连接到MySQL数据库的Java / JPA2.0(EclipseLink)应用程序。我的意图是使用db.properties
文件传递JAR文件。 db.properties
应包含服务器主机地址,用户名,密码等,以便最终用户可以将其插入并开始在项目中使用JAR。
目前,我只是使用Netbeans创建一个带有凭据的persistence.xml
文件,并且该文件有效。但是如何实现属性文件?
我的EntityManager类:
public class Factories {
private static final EntityManagerFactory entityManagerFactory = buildEntityManagerFactory();
private static EntityManagerFactory buildEntityManagerFactory() {
try {
return Persistence.createEntityManagerFactory("MyPU");
} catch (Exception ex) {
throw new ExceptionInInitializerError(ex);
}
}
public static EntityManager getEntityManager() {
return entityManagerFactory.createEntityManager();
}
}
由于
答案 0 :(得分:2)
您可以使用createEntityManagerFactory()
方法的双参数版本。第二个参数(Map)可用于将包括凭据的属性传递给数据库。因此,您可以使用密钥javax.persistence.jdbc.user
和javax.persistence.jdbc.password
以及相应的值传递地图。
example in the EclipseLink wiki演示了如何实现这一点,尽管它使用EclipseLink提供的类来实现这一目标:
import static org.eclipse.persistence.config.PersistenceUnitProperties.*;
...
Map properties = new HashMap();
// Ensure RESOURCE_LOCAL transactions is used.
properties.put(TRANSACTION_TYPE,
PersistenceUnitTransactionType.RESOURCE_LOCAL.name());
// Configure the internal EclipseLink connection pool
properties.put(JDBC_DRIVER, "oracle.jdbc.OracleDriver");
properties.put(JDBC_URL, "jdbc:oracle:thin:@localhost:1521:ORCL");
properties.put(JDBC_USER, "scott");
properties.put(JDBC_PASSWORD, "tiger");
// Configure logging. FINE ensures all SQL is shown
properties.put(LOGGING_LEVEL, "FINE");
properties.put(LOGGING_TIMESTAMP, "false");
properties.put(LOGGING_THREAD, "false");
properties.put(LOGGING_SESSION, "false");
// Ensure that no server-platform is configured
properties.put(TARGET_SERVER, TargetServer.None);
// Now the EntityManagerFactory can be instantiated for testing using:
Persistence.createEntityManagerFactory(unitName, properties);
请注意,也可以通过接受属性的EntityManagerFactory.createEntityManager()
方法执行此操作。但是,如果仔细阅读EclipseLink auditing example,您会发现共享连接池(其属性派生自persistence.xml)也会被创建,并且正在使用的实际连接将取决于您是否正在执行读取或写道。