Changing Persistence Unit dynamically - JPA

2019-01-08 16:05发布

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)

3条回答
小情绪 Triste *
2楼-- · 2019-01-08 16:10

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.
查看更多
该账号已被封号
3楼-- · 2019-01-08 16:17

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();
查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-01-08 16:18

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

查看更多
登录 后发表回答