Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing Persistence Unit dynamically - JPA

Persistence units in persistence.xml are created during building the application. As I want to change the database url at runtime, is there any way to modify the persistence unit at runtime? I supposed to use different database other than pre-binded one after distributed.

I'm using EclipseLink (JPA 2.1)

like image 816
N K Avatar asked Sep 03 '13 04:09

N K


2 Answers

Keep the persistence unit file (Persistence.xml) as it's. You can override the properties in it as follows.

EntityManagerFactory managerFactory = null;
Map<String, String> persistenceMap = new HashMap<String, String>();

persistenceMap.put("javax.persistence.jdbc.url", "<url>");
persistenceMap.put("javax.persistence.jdbc.user", "<username>");
persistenceMap.put("javax.persistence.jdbc.password", "<password>");
persistenceMap.put("javax.persistence.jdbc.driver", "<driver>");

managerFactory = Persistence.createEntityManagerFactory("<current persistence unit>", persistenceMap);
manager = managerFactory.createEntityManager();
like image 108
N K Avatar answered Nov 19 '22 17:11

N K


You can use Persistence.createEntityManagerFactory(Map) to pass properties to choose the database URL and other settings.

like image 26
James Avatar answered Nov 19 '22 17:11

James