动态更改持久性单元 - JPA [英] Changing Persistence Unit dynamically - JPA

查看:128
本文介绍了动态更改持久性单元 - JPA的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我正在使用EclipseLink(JPA 2.1)

I'm using EclipseLink (JPA 2.1)

推荐答案

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

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

这篇关于动态更改持久性单元 - JPA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆