何时使用EntityManager.clear()? [英] When to Use EntityManager.clear()?

查看:435
本文介绍了何时使用EntityManager.clear()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

自定义的JPA映射类有一个方法:

  removeUser()

1.执行'DELETE'HQL查询删除用户
2.调用getEntityManager()。flush();
3.调用getEntityManager()。clear();

如果我正确理解了clear(),它将从上下文中删除所有持久化实体。 -source



然而, ,我还阅读了此处, >

 您应该定义明确的体系结构和设计准则,了解可以调用
clear()的位置。

什么时候调用clear()?有明确的指导方针?

解决方案

这篇文章解释了它。清除实体管理器清空其关联的高速缓存,强制新的数据库查询稍后在事务中执行。在使用事务绑定实体管理器时几乎不需要清除实体管理器。我看到有两个理由要清楚:在进行批量处理时,为了避免有一个巨大的缓存吃内存并增加了刷新时间,


  • 因为在执行完全绕过实体管理器缓存的DML或SQL查询时(如在您的示例中),长时间的脏检查

  • 。在这种情况下,缓存所持有的状态由于查询而不能反映数据库中的内容,所以您想清除缓存以避免这种不一致。


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

解决方案

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.

这篇关于何时使用EntityManager.clear()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆