我尝试将同一实体持久化到MySQL和Postgres数据库中(这主要是为了识别任何不一致之处,并解决双重写入时的任何问题细节 - 我在这里遇到了问题)。我找到的文章都描述了依赖于其他框架的解决方案。我正在尝试使用Glassfish 4.0开箱即用、JPA 2.1和EclipseLink 2.5作为JPA提供程序来解决这个问题。我使用Eclipse,并意识到IDE不支持在persistence.xml文件中配置多个持久性单元,因此我直接编写XML进行设置。
我原以为可以在代码中做如下操作(在同一方法中):
我原以为可以在代码中做如下操作(在同一方法中):
@PersistenceContext(name = "MyAppMySQLPU")
EntityManager emMySQL;
@PersistenceContext(name = "MyAppPostgresPU")
EntityManager emPostgres;
//...etc...
MyThing thing = new MyThing();
//...etc...
emMySQL.persist(thing);
emPostgres.persist(thing);
并使用一个包含以下内容的persistence.xml
文件:
<persistence-unit name="MyAppPostgresPU">
<jta-data-source>jdbc/PostgresPool_test</jta-data-source>
<class>model.MyThing</class>
</persistence-unit>
<persistence-unit name="MyAppMySQLPU">
<jta-data-source>jdbc/MySQLPool_test</jta-data-source>
<class>model.MyThing</class>
</persistence-unit>
当我这样做时,出现以下错误:
SEVERE: Exception while invoking class org.glassfish.persistence.jpa.JPADeployer prepare method
SEVERE: Exception while preparing the app
SEVERE: Exception while preparing the app : Could not resolve a persistence unit corresponding to the persistence-context-ref-name [MyAppPostgresPU] in the scope of the module called [MyApp]. Please verify your application.
但是,如果我只包含一个<persistence-unit>
短语(不管是哪一个),实体将被持久化到相关的数据库中——我只是无法想出如何同时使用两者(而不依赖于其他框架的持久化功能)。