在我的应用程序管理事务中,我要选择:
EntityManager
并调用clear()
。使用EntityManager
分享ThreadLocal
。EntityManager
。我对JPA没有多少经验。我的问题是哪一个在性能方面更好?
答案 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读取甚至可以给出具有不同内容的对象。但是如果通过相同的实体管理器重复读取,第二次读取将从实体管理器缓存中获取对象,因此较新的状态将不可见。