How can I make a JPA application access different databases?

后端 未结 2 1887
既然无缘
既然无缘 2020-12-04 00:42

I\'m writing a Java SE (desktop) application that has to access different databases all of which will have the same data model (same schema, tables, etc.). I want to reuse

2条回答
  •  囚心锁ツ
    2020-12-04 01:17

    You can create EntityManagerFactory at runtime by providing properties.

    Map properties = new HashMap();
    
    properties.put(TRANSACTION_TYPE, PersistenceUnitTransactionType.RESOURCE_LOCAL.name());
    properties.put(JDBC_DRIVER, driver);
    properties.put(JDBC_URL, db_url);
    properties.put(JDBC_USER, "userName");
    properties.put(JDBC_PASSWORD, "password");
    
    EntityManagerFactory factory = Persistence.createEntityManagerFactory("PERSISTENT_UNIT_NAME", properties);
    

    Also you can try having a property file from which properties will be loaded at runtime into map. Therefore it will decouple the database configuration from code.

    Edit : The property keys(JDBC_URL etc) are vendor specific, they should be replaced accordingly.

提交回复
热议问题