【问题标题】:Dynamic JPA Connection动态 JPA 连接
【发布时间】:2011-05-05 14:23:26
【问题描述】:

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

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

那么,我的问题是如何最好地解决这个问题?

【问题讨论】:

    标签: java jpa multiple-databases


    【解决方案1】:

    我也在研究这个问题,到目前为止,我发现以下博客文章描述了一种方法 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");
    }
    
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-09
    • 2018-05-06
    • 1970-01-01
    • 1970-01-01
    • 2016-06-13
    • 1970-01-01
    • 2021-12-14
    • 2012-11-24
    相关资源
    最近更新 更多