Java 动态更改持久性单元 - JPA

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18583881/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 09:15:12  来源:igfitidea点击:

Changing Persistence Unit dynamically - JPA

javajpapersistence.xml

提问by N K

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.

persistence.xml 中的持久性单元是在构建应用程序期间创建的。由于我想在运行时更改数据库 url,有没有办法在运行时修改持久性单元?我应该在分发后使用不同的数据库而不是预先绑定的数据库。

I'm using EclipseLink (JPA 2.1)

我正在使用 EclipseLink (JPA 2.1)

采纳答案by N K

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

保持持久性单元文件 (Persistence.xml) 不变。您可以按如下方式覆盖其中的属性。

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

回答by Grim

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.jarwith persistence.xmlinside, 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.
  • System-Class-Loader(通常是 URLClassLoader,包含实体)
    • JPA-Class-Loader
      • 用里面加载你的jpa.jarpersistence.xml从 Application-Class-Loader 中指定 Database-Configuration
      • 实例化您的 entityManager/session-factory。
      • 加载使用数据库所需的任何插件。执行单元测试 (;D) 和插件集成测试。

回答by James

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

您可以使用 Persistence.createEntityManagerFactory(Map) 传递属性来选择数据库 URL 和其他设置。