问题描述
我一直认为,将在事务之前(在entityManager.getTransaction().begin()
之前)获取的实体与持久性上下文分离(同时使用相同的实体管理器来获取与处理事务相同的实体).实际上,每次我管理事务时,我都必须显式合并从其外部获取的实体.如果没有,则更新不会反映在数据库中.
I always thought that entities fetched before a transaction (before entityManager.getTransaction().begin()
) were detached from the persistence context (while using the same entity manager to fetch entities as to handle the transaction). In fact, every time I was managing transactions, I had to explicitly merge entities that were fetched outside of it. If I didn't, updates were not reflected in the database.
但是最近,我与一位经历了相反情况的同事进行了讨论.他必须明确分离事务之前获取的每个实体,以避免更新数据库.
But recently, I had a discussion with a colleague who experienced this situation the opposite way. He had to explicitly detach every entities fetched before transaction to avoid updating database.
我们的代码之间的唯一区别是我的persistence.xml
文件是2.0版,而他的文件是1.0版.但是他在代码中使用的是JPA 2.1.是这种奇怪行为的原因,还是我在这里不见了?
The only difference between our codes is that my persistence.xml
file is version 2.0 and his is version 1.0. But he is using JPA 2.1 in his code. Is that the reason for this strange behavior or is there something I'm missing here?
我们都使用Hibernate作为实现.
We both use Hibernate as implementation.
推荐答案
PersistenceContext可能有两个作用域:
PersistenceContext may have two scopes:
- 交易范围
- EXTENDED-SCOPE
交易范围
仅在EntityManager由容器管理时发生.在这种情况下,只要存在当前事务,就可以激活当前的PersistenceContext.
Occurs only when EntityManager is container-managed. In this case, current PersistenceContext is active as long as current transaction exists.
EXTENDED-SCOPE
在EntityManager由应用程序管理(默认)或容器管理(EntityManager需要注释:@PersistenceContext( type=PersistenceContextType.EXTENDED)
)时发生.
Occurs when EntityManager is application-managed (be default) or container-managed (EntityManager needs annotation: @PersistenceContext( type=PersistenceContextType.EXTENDED)
).
长话短说:EXTENDED-SCOPE表示当前的PersistenceContext只要您的bean生存就可以生存.
Long story short: EXTENDED-SCOPE means that current PersistenceContext lives as long as your bean lives.
这篇关于是从外部事务中获取的实体是受管理的还是分离的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!