java - 在一个事务中组合 JPA 和 JDBC 操作

标签 java postgresql jpa jdbc openjpa

因此,我有一个应用程序,其中包含一些遗留 JDBC 调用,我需要使用一些额外的 JPA 操作进行更新。我需要能够将 JDBC 调用和 JPA 调用作为同一个数据库事务的一部分。如果重要的话,我正在使用 OpenJPA 2.1.1 和 Postgres 9.1。下面的代码似乎可以正常工作——我已经运行了一些基本测试,并且 JDBC 和 JPA 语句都执行了;任何一个中的错误都会导致这对语句没有发生(例如,它们是同一个数据库事务的一部分)。是否有任何我没有发现的问题 - 我违反了一些最佳实践,或者我不能以这种方式重新使用 Connection 对象的其他原因?

EntityManager em = _em; //acquired from OpenJPA
em.getTransaction().begin();
Connection conn;
try {
  OpenJPAEntityManager oem = (OpenJPAEntityManager) em.getDelegate();
  conn = oem.getConnection();
  PreparedStatement ps = conn.prepareStatement(myStatement);
  //initialize parameters in ps
  ps.executeUpdate();
  em.merge(myJpaObject);
  em.getTransaction().commit();
} finally {
    if (ps != null && !ps.isClosed()) {
      ps.close();
    }
    if (em.getTransaction().isActive()) {
    em.getTransaction().rollback();
  }
}

谢谢!

最佳答案

只要稍作调整,我认为应该没问题。

值得注意的是what the OpenJPA documentation has to say about it :

The returned connection is only guaranteed to be transactionally consistent with other EntityManager operations if the EntityManager is in a managed or non-optimistic transaction, if the EntityManager has flushed in the current transaction, or if you have used the OpenJPAEntityManager.beginStore method to ensure that a datastore transaction is in progress. Always close the returned connection before attempting any other EntityManager operations. OpenJPA will ensure that the underlying native connection is not released if a datastore transaction is in progress.

你的交易没有管理,但我认为它是不乐观的。此外,您在启动事务和执行 JDBC 之间没有完成任何 JPA 工作,所以我认为您可能属于“如果 EntityManager 已在当前事务中刷新”的情况。

您没有做的一件事是在继续使用 JPA 之前关闭连接。我假设 OpenJPA 不返回它正在使用的实际连接,但它周围的一些包装器应该在 OpenJPA 恢复工作之前关闭。

关于java - 在一个事务中组合 JPA 和 JDBC 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13501230/

相关文章:

ruby-on-rails - rails 范围内的时区独立到期日比较

php - 如何使用 PHPs PDO 层设置 postgresql 客户端字符集?

Java从mysql中检索正确格式的日期记录

java - 编码时 JAXB 展平实体列表

java - 访问 stub 方法的可变参数以返回不同的结果

java - Java 中的 copy() 方法 - 有这样的事情吗?

sql - 如何在 postgresql 中以不同方式更新共享相同 id 的每一行?

java - 自 Wildfly 15 起,Arquillian 托管测试不再有效

java - SSLEngine 但没有委派任务

java - Spring +JPA : object does not get fetched from the database