簡體   English   中英

動態JPA連接

[英]Dynamic JPA Connection

我有一個相當標准的Java EE6 Web應用程序使用JPA 2,依賴注入連接到MySQL數據庫,一切正常。 我現在要做的是讓這個應用程序與我們在客戶端站點安裝的其他應用程序的數據庫進行交互 - 基本上作為我們其他應用程序安裝的單一控制點。

我正在努力的是如何最好地與其他數據庫進行交互。 理想情況下,我想為每次安裝創建一個EntityManager並使用JPA進行交互,但我看不到任何設置方法。 例如,我可能有一個應用程序類型的5個安裝(以及數據庫),並且主控制應用程序在運行時之前不會知道其他安裝。 這似乎排除了使用EntityManager的依賴注入和所有自動事務demacation等等。替代選項是只創建一個DataSource並手動進行交互。 雖然靈活,但這顯然需要更多的努力。

所以,我的問題是如何最好地解決這個問題?

我也在研究這個問題,到目前為止,我發現以下博客文章描述了一種方法來做到這一點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");
}

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM