gpt4 book ai didi

java - "associated with persistence context"是什么意思?

转载 作者:行者123 更新时间:2023-12-03 20:24:54 26 4
gpt4 key购买 nike

在本文档中 http://docs.oracle.com/javaee/5/tutorial/doc/bnbqw.html , 它说

Managed entity instances have a persistent identity and are associated with a persistence context.Detached entity instances have a persistent identify and are not currently associated with a persistence context.

所以我想了解“与持久性上下文相关联”是什么意思?

最佳答案

您可以将Persistence Context 视为能够存储实体 的容器使用 Entity Manager 管理并与数据库同步。下图描述了 JPA 类和接口(interface)之间的依赖关系:

Relationships between JPA classes and interfaces


将实体与持久性上下文相关联的过程可以通过执行以下操作来实现:

  • EntityManager.persist 新创建实体的方法
  • EntityManager.merge 分离实体上的方法
  • EntityManager.find 具有给定实体类型及其主键的方法
  • EntityManager.createNativeQueryEntityManager.createNamedQueryEntityManager.createQuery 方法以及基于 SQL/JPQL/CriteriaAPI 的查询

如果是事务范围的容器管理的持久性上下文,则需要在事务范围内调用这些方法。

@Entity
public class Employee {
@Id
private int id; //determines persistent identity
public Employee(int id) { this.id = id; }
}

持久身份允许通过其主键在所有相同类型的实体中定位实体,并在刷新或提交持久性上下文(手动刷新/提交或自动)的情况下同步到数据库。

Employee emp = new Employee(1);

em.persist(emp);
boolean isManaged = em.contains(emp); //true, managed, id=1
boolean isFound = Objects.equals(emp, em.find(Employee.class, 1)); //true

持久化实体会导致它成为托管的(与持久化上下文相关联)。不代表实体同步到数据库。


可以通过执行以下命令来实现解除实体与持久性上下文关联的过程:

    受管实体上的
  • EntityManager.detachEntityManager.remove 方法;它们之间的区别在于分离的实体保留在基础数据库中,因为删除的实体不是
  • EntityManager.commit, EntityManager.rollback, EntityManager.clear, EntityManager.close 影响持久化的方法背景
  • 序列化作为将其传递到另一层或通过远程接口(interface)发送的结果
...
em.detach(emp);
isManaged = em.contains(emp); //false, detached, id=1
isFound = Objects.equals(emp, em.find(Employee.class, 1)); //false

虽然分离的实体仍然分配了持久标识,但它不再与持久上下文相关联,因此与数据库同步。因此,对分离实体的任何更改都不会被持久化和提交,除非它被合并到持久化上下文中。在这种情况下,实体可能已被另一方覆盖,因此变得陈旧,因此需要清除/重新分配正在合并的实体的 ID。

关于java - "associated with persistence context"是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26371556/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com