Reputation: 41919
A custom JPA mapper class has a method:
removeUser()
1. execute 'DELETE' HQL query to remove user
2. call getEntityManager().flush();
3. call getEntityManager().clear();
If I understand clear() correctly, it will remove from context all persistent entities. -source
However, I also read here,
you should define clear architecture- and design guidelines about where a
clear() can be called.
What are clear guidelines on when to call clear()?
Upvotes: 57
Views: 120010
Reputation: 41410
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.
Upvotes: 3
Reputation: 691865
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:
Upvotes: 69
Reputation: 470
Yeas, it's exactly depends on the architecture style of the platform as documentation points.
As you see depends on the cases, architecture and style for your platform. Directly for your method - it's not a good practice to flush and clear cache per method, it's a anti pattern method.
Upvotes: 9