如何使JPA应用程序访问不同的数据库? [英] How can I make a JPA application access different databases?
问题描述
我正在编写一个Java SE(桌面)应用程序,该应用程序必须访问不同的数据库,所有这些数据库都将具有相同的数据模型(相同的架构,表等).我想重用在每个数据库前面的Java EE应用程序中已经使用过的JPA实体.
I'm writing a Java SE (desktop) application that has to access different databases all of which will have the same data model (same schema, tables, etc.). I want to reuse the JPA Entities that I already use in a Java EE application that front each database.
要重用现有的entity.jar文件,我必须使用具有resource_local数据源的另一个persistence.xml将其重新打包.那是构建时间上的不便,但不是一个大问题.
To reuse the existing entity.jar file I'll have to repackage it with a different persistence.xml that has a resource_local data source. That's an build time inconvenience but not a big problem.
问题是我的桌面应用程序将只能使用persistence.xml文件中定义的数据源.我可以定义多个持久性单元并选择在运行时使用哪个持久性单元,但是当添加新数据库时,我将不得不更改persistence.xml并更新所有桌面二进制文件.
The problem is that my desktop application will be limited to using the datasource defined in the persistence.xml file. I could define multiple persistence units and select which one to use at runtime, but when a new database is added I'll have to change the persistence.xml and update all the desktop binaries.
我希望能够在每个用户可以配置的.properties文件中定义新的数据源.在运行时是否有任何方法可以覆盖或添加到persistence.xml中声明的持久性单元?
I'd like to be able to define new data sources in a .properties file that each user could configure. Is there any way to override or add to the persistence units declared in the persistence.xml at runtime?
我不想仅使用Web服务接口来构建Java EE应用程序以支持该桌面应用程序. Java EE应用程序具有不同的用途,我想将桌面功能保留在桌面应用程序中.
I don't want to build out the Java EE applications with web service interfaces just to support this desktop application. The Java EE applications have a different purpose and I want to keep the desktop functionality in the desktop application.
谢谢.
推荐答案
您可以在运行时通过提供属性来创建EntityManagerFactory.
You can create EntityManagerFactory at runtime by providing properties.
Map<String, Object> properties = new HashMap<String, Object>();
properties.put(TRANSACTION_TYPE, PersistenceUnitTransactionType.RESOURCE_LOCAL.name());
properties.put(JDBC_DRIVER, driver);
properties.put(JDBC_URL, db_url);
properties.put(JDBC_USER, "userName");
properties.put(JDBC_PASSWORD, "password");
EntityManagerFactory factory = Persistence.createEntityManagerFactory("PERSISTENT_UNIT_NAME", properties);
您还可以尝试拥有一个属性文件,该属性文件将在运行时从中加载到map中.因此,它将使数据库配置与代码脱钩.
Also you can try having a property file from which properties will be loaded at runtime into map. Therefore it will decouple the database configuration from code.
属性键(JDBC_URL等)是供应商特定的,应相应地替换它们.
Edit : The property keys(JDBC_URL etc) are vendor specific, they should be replaced accordingly.
这篇关于如何使JPA应用程序访问不同的数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!