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()?
clear. Clear the persistence context, causing all managed entities to become detached. Changes made to entities that have not been flushed to the database will not be persisted.
Using EntityManagerFactory approach allows us to use callback method annotations like @PrePersist, @PostPersist,@PreUpdate with no extra configuration. Using similar callbacks while using SessionFactory will require extra efforts.
To delete a record from database, EntityManager interface provides remove() method. The remove() method uses primary key to delete the particular record.
JPA EntityManager is used to access a database in a particular application. It is used to manage persistent entity instances, to find entities by their primary key identity, and to query over all entities.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With