从persistence.xml创建实体管理器工厂后如何修改属性 [英] how to modify properties after create entity manager factory from persistence.xml

查看:111
本文介绍了从persistence.xml创建实体管理器工厂后如何修改属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

i have a persistence.xml in META-INF/ folder:

<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>

在Java代码中,我从该persistence.xml创建实体管理器文件

in java code i create entity manager facotry from that persistence.xml

_emf = Persistence.createEntityManagerFactory("dev");
_em = _emf.createEntityManager();

但是我只想动态更改jdbc url/user/password以进行测试,我的计划是将这些参数保存在配置文件中并根据需要读取它们,因此在创建entitymanagerfactory后有没有办法更新它们从persistence.xml?所以它是这样的:

however i want do change only the jdbc url/user/password dynamically for test, my plan is to save those parameters in a config file and read them as needed, so is there a way i can update them after i create entitymanagerfactory from persistence.xml? so it would like this:

_emf = Persistence.createEntityManagerFactory("dev");
_emf.setProperties("url", "test_url");
    ... other setts here ...
_em = _emf.createEntityManager();

谢谢

推荐答案

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

When you create the EntityManagerFactory, you can pass a set of properties that will override what is defined in persistence.xml, e.g.:

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

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

If you want to modify the connection properties after the EntityManagerFactory was created, you must recreate it by calling createEntityManagerFactory() again.

这篇关于从persistence.xml创建实体管理器工厂后如何修改属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆