Changing Persistence Unit dynamically - JPA

﹥>﹥吖頭↗ 提交于 2019-11-27 07:19:53
N K

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

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

In Long-lived Session Architecture you should create a Plug-in-Framework.

Therefore you need to create a different Thread-Group and Class-Repository.

This might be your Class-Loader-Tree

  • System-Class-Loader (usually a URLClassLoader, contains the Entitys)
    • JPA-Class-Loader
      • Load your jpa.jar with persistence.xml inside, specify the Database-Configuration from Application-Class-Loader
      • Instanciate your entityManager/session-factory.
      • Load any plugin you need to work with the DataBase. Execute Unit-Tests (;D) and Plugin-Integration-Tests.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!