How to merge two transactions for different schemes into one? How to merge two transactions for different schemes into one? oracle oracle

How to merge two transactions for different schemes into one?


It seems like you are managing transactions yourself. Typically the Java EE container would handle such cases for you. JTA uses two-phase commits in this case which is exactly for situations like this.

If your are managing transactions yourself, it is a bit more complicated. The problem is that if you commit the first and the commit of the second one fails, you cannot rollback the first any more.

In your case I suggest the follwing. Typically a commit can only fail, because the Hibernate doesn't immediately write changes to the database if you modify an object. This happens when Hibernate performs a "flush". This is done automatically before queries are executed which may be affected by objects you already modified and also before the transaction is committed.

So you could simply flush both entity managers first, which will write all the changes to both databases, and then commit both transaction, which shouldn't fail anymore.

Something like this:

entityManager1.flush();entityManager2.flush();entityManager1.getTransaction().commit();entityManager2.getTransaction().commit();

However I recommend to don't manage such cases manually and instead let the container do this.