简体   繁体   English

SE应用程序的JPA persistence.xml数据源

[英]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="..."/> . 各种来源(例如Oracle )都说您必须在persistence.xml中为Java SE应用程序指定jdbc连接详细信息,这些Java SE应用程序通过<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. 当我添加实体类时,我必须向每个持久性单元添加<class>MyClass</class> 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. 如果要更改环境中使用的数据库,则需要弄弄persistence.xml并重新构建应用程序。 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? 是否可以通过某种方式使<jta-data-source><non-jta-data-source>在Java SE环境中执行适当的操作?

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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