When to Use EntityManager.clear()?

The articles explains it. Clearing the entity manager empties its associated cache, forcing new database queries to be executed later in the transaction. It’s almost never necessary to clear the entity manager when using a transaction-bound entity manager. I see two reasons to clear:

  • when doing batch processing, in order to avoid having a giant cache eating memory and increasing the time to flush because of long dirty checks
  • when you’re doing DML or SQL queries, which completely bypass the entity manager cache (as in your example). In this case, the state held by the cache doesn’t reflect what is in the database because of the queries, so you want to clear the cache to avoid this inconsistency.

Leave a Comment