When to Use EntityManager.clear()?

后端 未结 2 1628
长情又很酷
长情又很酷 2020-12-01 06:07

A custom JPA mapper class has a method:

removeUser()

1. execute \'DELETE\' HQL query to remove user
2. call getEntityManager().flush();
3. call getEntityMan         


        
2条回答
  •  有刺的猬
    2020-12-01 06:44

    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.

提交回复
热议问题