Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

hibernate - When to Use EntityManager.clear()?

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()?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...