Changing Persistence Unit dynamically - JPA

前端 未结 4 1279
被撕碎了的回忆
被撕碎了的回忆 2020-11-29 03:26

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

4条回答
  •  囚心锁ツ
    2020-11-29 04:07

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

    EntityManagerFactory managerFactory = null;
    Map persistenceMap = new HashMap();
    
    persistenceMap.put("javax.persistence.jdbc.url", "");
    persistenceMap.put("javax.persistence.jdbc.user", "");
    persistenceMap.put("javax.persistence.jdbc.password", "");
    persistenceMap.put("javax.persistence.jdbc.driver", "");
    
    managerFactory = Persistence.createEntityManagerFactory("", persistenceMap);
    manager = managerFactory.createEntityManager();
    

提交回复
热议问题