0

As a result of some transaction problems with JPA, I am managing some of these manually, following a standard like:

EntityTransaction txn = em.getTransaction();
txn.begin();
try {
    em.persist(myentity);
    txn.commit();
} 
finally {
   if (txn.isActive())
      txn.rollback(); 
}

While others are managed directly from entitymanager using autocommit (set in my framework):

 em.persist(myentity);

What are the problems using this approach?

MWiesner
  • 8,868
  • 11
  • 36
  • 70
Jonio
  • 1,213
  • 2
  • 15
  • 35
  • This is not a bad way to do transactions, but you have to make sure that in case of (some specifically chosen) exceptions, you call `setRollbackOnly(true)` so that you will rollback in your `finally` statement – Pierre Demeestere Nov 09 '22 at 16:53
  • There is no auto commit in JPA, and the feature itself is one they do not recommend within Hibernate. See https://stackoverflow.com/questions/23100888/why-is-hibernate-connection-autocommit-true-not-recommended-in-hibernate and I'm sure others can think of tons of good reasons it isn't the best choice to use. It seems reasonable to avoid boiler plate transaction begin/commit handling for a single call, but transactional scopes rarely stay that simple, and you need to have much better exception handling to deal with the EntityManager context and its state after a problem with auto commit – Chris Nov 09 '22 at 19:49
  • Not mentioned but important and I didn't see it mentioned: entity handling via merge and persist can span multiple SQL statements. Auto commit will allow some to get in and stay in, as there is no transaction to roll them back. I don't know how you/hibernate handles getting the persist call to 'flush' to the database in your auto commit situation, but if an error happens, you cannot know what is in the database at all (without checking DB data and logs that is) - not just the EntityManager state – Chris Nov 09 '22 at 19:55

0 Answers0