[英]When does a persistent object become detached
有人可以通过一个示例将确切的持久对象变成分离对象来帮助我理解吗?
It becomes detached when: 在以下情况下它将分离:
Depends on the persistence context you are using (transaction or extended). 取决于您使用的持久性上下文(事务或扩展)。 See this link for a description.
请参阅此链接以获取描述。 Basically as per the other answer EXCEPT that answer misses off detachment when a transaction is committed when using transaction PersistenceContext
基本上与其他答案不同,当使用事务PersistenceContext提交事务时,答案会错过分离
I think that the best understanding on when the entity is detached is looking at what JPA specification says about entity's lifecycle. 我认为,关于何时分离实体的最佳理解是查看JPA规范对实体生命周期的描述。
A detached entity instance is an instance with a persistent identity that is not (or no longer) associated with a persistence context.
分离的实体实例是具有与(或不再)与持久性上下文关联的持久性身份的实例。
This means that an entity may be considered as detached even it is newly created. 这意味着即使实体是新创建的,也可以将其视为已分离。 Let's say that our entity
A
has its id marked as @Id @GeneratedValue
. 假设我们的实体
A
的ID标记为@Id @GeneratedValue
。 So basically the JPA provider will take care of assigning an id. 因此,基本上,JPA提供者将负责分配ID。 But if you will specify
A
's id explicitly (eg a.setId(1)
) and then pass it to persist()
you will get an Exception. 但是,如果您将显式指定
A
的ID(例如a.setId(1)
),然后将其传递给persist()
,则会得到异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.