2

In JPA, is it guaranteed that the transactional semantics (=effects from the database point of view) of the following snippets are identical?

Snippet A

EntityManager em = ...
List<Work> workList = ...
for(Work work : workList)
{
  doWork(work); //may change some entities
}
em.getTransaction().commit();

Snippet B

EntityManager em = ...
List<Work> workList = ... 
for(Work work : workList)
{
  doWork(work); //may change some entities
  em.flush(); 
  em.clear();
}
em.getTransaction().commit();


In other words:
Can em.clear() after em.flush() change transactional semantics (beside the fact the em.clear() detaches all entities; it can be assumed that doWork() is capable of dealing with that)?

MRalwasser
  • 15,605
  • 15
  • 101
  • 147

1 Answers1

1

Flush pushes all changes into the database; clear will do nothing to rollback or undo those changes as it only affects what is currently loaded in the context. em.flush() followed by em.clear() is a common pattern used to reduce the number of loaded entities used in a long running transaction while work proceeds in the same transaction.

Chris
  • 20,138
  • 2
  • 29
  • 43