Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to modify properties after create entity manager factory from persistence.xml

Tags:

hibernate

jpa

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>

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

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

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();

thanks

like image 674
user468587 Avatar asked Dec 12 '22 10:12

user468587


1 Answers

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

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

like image 159
David Levesque Avatar answered May 18 '23 16:05

David Levesque