TL;DR: use EntityManager.clear
if you are about to perform a set of JPA operations where you don't need a majority of the entities that are already loaded
I recently had a performance issue which prompted me to ask how to get extra logging. Before I got the answer I found out how to fix the issue and that's through EntityManager.clear()
.
One use case I'd use it for is to isolate operations that may be intensive and load up a lot of entities for the entity manager to manage. In my case there's a step where I perform authorization checks. For most of the business logic in the remainder of the transaction, I don't need most of the data that it would have used (user profile, low level entity access checks, etc).
What I found was even if I don't use them it stays for the rest of the session and will eventually need to be flushed even if my processing was done already.
By doing a clear
before the flush happens it releases them from the entity manager and are no longer managed.