2010-11-05 70 views
9

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

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

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

回答

5

我也期待这个,到目前为止,我已经找到一个描述办法做到这一点 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"); 
} 

} 
+0

persistance.xml根幻灯CT? – 2017-01-07 22:02:18

+0

@ e-info128 no在正常位置:src/main/resources/META-INF/persistence.xml(https://stackoverflow.com/questions/10871109/where-to-put-persistence-xml-in-library -jar-使用-行家) – AmanicA 2017-01-08 19:45:24