0

I'm using JPA for a desktop software. The end user needed a frame to change the Database connection dynamically (on the fly) by changing the persistance.xml data. I've tried using below code (which I found here) and modified but so far unsuccessful in changing the database connection.

EntityManagerFactory managerFactory = EntityManagerSingleton.getInstance().getEntityManagerFactory();
managerFactory = null;
Map<String, String> persistenceMap = new HashMap<String, String>();

persistenceMap.put("javax.persistence.jdbc.url", "jdbc:mysql://"+dbHost+":"+dbPort+"/"+dbName+"?zeroDateTimeBehavior=convertToNull");
persistenceMap.put("javax.persistence.jdbc.user", dbUser);
persistenceMap.put("javax.persistence.jdbc.password", dbPwd);
persistenceMap.put("javax.persistence.jdbc.driver","com.mysql.jdbc.Driver");

managerFactory = Persistence.createEntityManagerFactory("Persistance Unit Name", persistenceMap);
manager = managerFactory.createEntityManager();

I'm using a singleton class to get the entity manager factory so it will create only one connection to the database and only one Entity manager factory. Above managerFactory is the returned value from the singleton class. So can anyone tell me what I was doing wrong or a better way to do this?

Thanuj
  • 139
  • 2
  • 12
  • and EMF corresponds to a database. Once created, that is it. – Neil Stockton Sep 23 '16 at 10:08
  • It's because I've made it as a singleton object? [link](http://stackoverflow.com/questions/18583881/changing-persistence-unit-dynamically-jpa) This question shows how to do it, but for that moment only. Are you suggesting me to not to use singleton? – Thanuj Sep 23 '16 at 10:24
  • 1
    I'm not suggested anything. I'm saying an EMF corresponds to a database; a JPA provider will create a connection pool at startup of the EMF. If you want to change the pool then you close the EMF and create a new one ... that is the portable way – Neil Stockton Sep 23 '16 at 10:26
  • Thanks man, that worked flawlessly. I've changed `managerFactory = null; ` to `managerFactory.close();` – Thanuj Sep 23 '16 at 10:40

0 Answers0