如何在从persistence.xml创建实体管理器工厂后修改属性

use*_*587 4 hibernate jpa

我在META-INF /文件夹中有一个persistence.xml:

<persistence-unit name="dev" transaction-type="RESOURCE_LOCAL">
<properties>
  <property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost:5432/events" />
  <property name="javax.persistence.jdbc.user" value="postgres" />
  <property name="javax.persistence.jdbc.password" value="" />
  <property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver" />
  <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect" />
  <property name="hibernate.connection.provider_class" value="org.hibernate.connection.C3P0ConnectionProvider" />
  <property name="hibernate.show_sql" value="false" />
</properties>
</persistence-unit>
Run Code Online (Sandbox Code Playgroud)

在java代码中,我从该persistence.xml创建实体管理器facotry

_emf = Persistence.createEntityManagerFactory("dev");
_em = _emf.createEntityManager();
Run Code Online (Sandbox Code Playgroud)

但是我想要动态更改jdbc url/user/password进行测试,我的计划是将这些参数保存在配置文件中并根据需要读取它们,所以有一种方法可以在我从持久性创建entitymanagerfactory后更新它们. XML?所以它想这样:

_emf = Persistence.createEntityManagerFactory("dev");
_emf.setProperties("url", "test_url");
    ... other setts here ...
_em = _emf.createEntityManager();
Run Code Online (Sandbox Code Playgroud)

谢谢

Dav*_*que 13

创建EntityManagerFactory时,可以传递一组将覆盖persistence.xml中定义的属性,例如:

Properties props = new Properties();
props.setProperty("javax.persistence.jdbc.url", "test_url");
_emf = Persistence.createEntityManagerFactory("dev", props);
Run Code Online (Sandbox Code Playgroud)

如果要在创建EntityManagerFactory后修改连接属性,则必须通过createEntityManagerFactory()再次调用重新创建它.