我正在研究 JPA 文档并遇到以下几行:
Entity relationships for which the locked entity contains the foreign key will also be locked, but not the state of the referenced entities (unless those entities are explicitly locked). Element collections and relationships for which the entity does not contain the foreign key (such as relationships that are mapped to join tables or unidirectional one-to-many relationships for which the target entity contains the foreign key) will not be locked by default.
来自here (PessimisticLockScope.NORMAL
)
我想知道如何解释这些行。如果 PessimisticLockScope
设置为 EXTENDED
那么连接表中的行也被锁定(但不是相关实体本身),所以当使用 NORMAL
值时什么会被锁?对于确定的实体行(或者如果继承策略是 JOINED
或 TABLE_PER_CLASS
或者如果有 SecondaryTable
的话),但是“实体关系”是什么意思:
Entity relationships for which the locked entity contains the foreign key will also be locked
在 PessimisticLockScope.NORMAL
的上下文中?
最佳答案
实体关系映射到数据库 FK 关联。
PessimisticLockScope.NORMAL
将发出一个相当激进的数据库独占锁定:
- 实体分离表行
- 在连接表继承结构中,基表和子类表都将被锁定
- 所有
@ManyToOne
和@OneToOne
具有实际 FK 关系的关联表行(例如,与@JoinColumn
的一侧)。但这意味着您不能更改 FK 信息,这意味着您不能将其设置为 null 或任何其他不同的值。因此只有 FK 列值被锁定,而不是其他表关联的 FK 行。
@OneToMany
、@ManyToMany
和非所有者 @OneToOne
和 @ManyToOne
关联不会进行被锁定,因为这些关联只有一个面向对象的等效项,并且锁定仅发生在数据库级别。
PessimisticLockScope.EXTENDED
也将扩展为 @OneToMany
和 @ManyToMany
关联。但同样,这仅适用于 FK 列值而不适用于整行。因此,此锁定将阻止向/从 @OneToMany
/@ManyToMany
关联添加/删除元素。它不会阻止更新包含的元素。为此,您必须锁定每个包含的实体。
关于java - JPA PessimisticLockScope.NORMAL 和锁定 "relationships",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24806909/