Java – combines JPA and JDBC operations in a single transaction

So I have an application with some legacy JDBC calls that I need to update with some additional JPA operations I need to be able to make JDBC calls and JPA calls as part of the same database transaction If it's important, I'm using openjpa 2.1 1 and Postgres 9.1 The following code seems to work - I ran some basic tests and both JDBC and JPA statements were executed; An error in either will cause the pair of statements not to occur (for example, they are part of the same DB transaction) Did I see any problems - I violated some best practices, or for other reasons I couldn't reuse the connection object in this way?

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

thank you!

Solution

Through an adjustment, I think it should be no problem

What the openjpa documentation has to say about it:

Your transaction is not regulated, but I don't think it's optimistic In addition, you haven't finished any JPA work between starting the transaction and executing the JDBC operation, so I think you may fall into the situation of "if the entitymanager has been refreshed in the current transaction"

One thing you didn't do was close the connection before continuing to use JPA I assume that openjpa does not return the actual connection it is using, but some of its wrappers should be closed before openjpa resumes work

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>