Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
458 views
in Technique[技术] by (71.8m points)

jpa 2.0 - How can I make a JPA application access different databases?

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 the JPA Entities that I already use in a Java EE application that front each database.

To reuse the existing entity.jar file I'll have to repackage it with a different persistence.xml that has a resource_local data source. That's an build time inconvenience but not a big problem.

The problem is that my desktop application will be limited to using the datasource defined in the persistence.xml file. I could define multiple persistence units and select which one to use at runtime, but when a new database is added I'll have to change the persistence.xml and update all the desktop binaries.

I'd like to be able to define new data sources in a .properties file that each user could configure. Is there any way to override or add to the persistence units declared in the persistence.xml at runtime?

I don't want to build out the Java EE applications with web service interfaces just to support this desktop application. The Java EE applications have a different purpose and I want to keep the desktop functionality in the desktop application.

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can create EntityManagerFactory at runtime by providing properties.

Map<String, Object> properties = new HashMap<String, Object>();

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...