JPA: How to not commit an EntityTransaction

Viewed 67

Let's say I have a scheduled job that regularly runs a database modification over a list of entities, all in one transaction. Depending on the situation, there might be lots to modify, or nothing at all.

entityManager.getTransation().begin();

for (MyEntity e : myEntityRepository.getAllDirtyEntities()) {
    myEntityRepository.cleanUp(e); // does some modification to e
}

entityManager.getTransaction().commit();

What is the best way to deal with scenarios where getAllDirtyEntities() returns nothing (= an empty List)?

  1. commit() anyway, even though nothing was changed
  2. rollback(), even though nothing was changed
  3. neither of the two: do nothing; let the entityTransaction get GC'd
  4. Avoid this scenario completely: query first, begin() & commit() the transaction only if there is something to do
1 Answers

I'd say performance-wise 3. is the best option but it might eat up memory depending on the implementation and frequency of the run. So, I'd go for 1. because it is the safest next-best performance option. 2. is probably slower und 4. is definitely slower.

Related