通过em.clear()重用实体管理器或创建新的实体管理器?

时间:2013-04-22 04:05:22

标签: jpa jpa-2.0 entitymanager

在我的应用程序管理事务中,我要选择:

  1. 在每次新交易之前使用一个EntityManager并调用clear()。使用EntityManager分享ThreadLocal
  2. 为每笔交易创建新的EntityManager
  3. 我对JPA没有多少经验。我的问题是哪一个在性能方面更好?

2 个答案:

答案 0 :(得分:8)

我建议每个事务创建一个新的EntityManager。这是JPA的设计方式。 EntityManager不应该是一个昂贵的对象来创建。 (虽然EntityManagerFactory非常昂贵,但请确保您只有其中之一)。

答案 1 :(得分:0)

okwap提供的链接非常有用。为了确保它不会漏过,并遵循董事会规则,我在这里复印一份:

- an EntityManager contains a persistence context, that will track
  everything read through it, so to avoid bloated memory, you should 
  acquire a new one, or clear it at some point
- if you read the same object through two different EntityManager you 
  will get different objects back, so will loose object identity, which 
  is something to consider 

基于此,我将补充说,如果在此期间由其他人执行数据库事务,则通过两个不同的EntityManager读取甚至可以给出具有不同内容的对象。但是如果通过相同的实体管理器重复读取,第二次读取将从实体管理器缓存中获取对象,因此较新的状态将不可见。