Dynamic JPA Connection

前端 未结 1 1284
北荒
北荒 2020-12-30 10:14

I have a fairly standard Java EE6 web application using JPA 2 with dependency injection connecting to a MySQL database and everything is working fine. What I would like to d

相关标签:
1条回答
  • 2020-12-30 11:12

    I'm also looking into this, and so far I have found the following blog post that describes a way to do it http://ayushsuman.blogspot.com/2010/06/configure-jpa-during-run-time-dynamic.html :

    Removed all your database properties from persistance.xml

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

    Changed your java file where you are configuring entityManager, in our case 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 讨论(0)
提交回复
热议问题