简体   繁体   中英

JPA persistence.xml data-source for SE app

Various sources (eg Oracle ) say that you have to specify jdbc connection details in your persistence.xml for Java SE apps which use JPA via things like <property name="javax.persistence.jdbc.url" value="..."/> .

This is a real pain when you want to run the app against different databases, for example local, test and production. I currently get around this by having multiple persistence-units that are all effectively the same but with different connection details, and then get the app to pick the right persistence-unit based on the environment that it is running in.

The problems with this are:

  • Duplication of config. When I add an Entity class I have to add <class>MyClass</class> to every persistence-unit. I would rather just specify it once.
  • Database connection config packaged with the app. If I want to change what database is being used in an environment, I need to fiddle with persistence.xml and re-build the app. I would rather have a config file in each of my environments which specifies the database credentials. That way, I could have many environments but just a single persistence-unit defined, and I could change the database credentials for a given environment by just editing one file in that environment and then re-starting the app.

Do you know of a better way to configure persistence? Is there some way of getting <jta-data-source> or <non-jta-data-source> to do something appropriate in a Java SE environment?

U can config it manually in code

Map<String, String> props = new HashMap<String, String>();
props.put("javax.persistence.jdbc.url", "YourURL");
EntityManagerFactory emf = Persistence.createEntityManagerFactory("UnitName", props);
EntityManager em = emf.createEntityManager();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM