2010-11-05 94 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