11

我有一个相当标准的 Java EE6 Web 应用程序,它使用 JPA 2 和依赖注入连接到 MySQL 数据库,一切正常。我现在想做的是让这个应用程序与我们在客户端站点上安装的其他应用程序的数据库进行交互——本质上充当我们其他应用程序安装的单点控制。

我正在努力解决的是如何最好地执行与其他数据库的交互。理想情况下,我想为每次安装创建一个 EntityManager 并使用 JPA 进行交互,但我看不到任何设置方法。例如,我可能有 5 个应用程序类型的安装(因此是数据库),而主控制应用程序直到运行时才知道其他安装。这似乎排除了使用 EntityManager 的依赖注入和所有自动事务破坏等。另一种选择是只创建一个 DataSource 并手动进行交互。虽然很灵活,但这显然需要更多的努力。

所以,我的问题真的是我如何最好地解决这个问题?

4

1 回答 1

7

我也在研究这个,到目前为止,我发现了以下博客文章,描述了一种方法 http://ayushsuman.blogspot.com/2010/06/configure-jpa-during-run-time-dynamic .html

从persistance.xml 中删除所有数据库属性

<persistence>
<persistence-unit name="jpablogPUnit" transaction-type="RESOURCE_LOCAL">
<class>com.suman.Company</class>
</persistence-unit>
</persistence>

更改了配置 entityManager 的 java 文件,在我们的例子中为 TestApplication.java

package com.suman;

import java.util.HashMap;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.apache.log4j.Logger;

/**
* @author Binod Suman
*/
public class TestApplication {

Logger log = Logger.getLogger(TestApplication.class);
public static void main(String[] args) {
TestApplication test = new TestApplication();
test.saveCompany();
}

public void saveCompany(){
log.info("Company data is going to save");
EntityManagerFactory emf;
Map properties = new HashMap();
properties.put("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
properties.put("hibernate.connection.url", "jdbc:mysql://localhost:3306/sumandb");
properties.put("hibernate.connection.username", "root");
properties.put("hibernate.connection.password", "mysql");
properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
properties.put("hibernate.show-sql", "true");
//emf = Persistence.createEntityManagerFactory("jpablogPUnit");
emf = Persistence.createEntityManagerFactory("jpablogPUnit",properties);
EntityManager entityManager = (EntityManager) emf.createEntityManager();
entityManager.getTransaction().begin();
Company company = new Company(120,"TecnoTree","Espoo, Finland");
entityManager.persist(company);
entityManager.getTransaction().commit();
log.info("Company data has been saved");
}

}
于 2011-03-08T15:50:01.960 回答