gpt4 book ai didi

java - JPA - 使用 mappedBy 属性定义拥有实体的区别

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:28:49 26 4
gpt4 key购买 nike

下面两个声明到底有什么区别

B是拥有方

@Entity
class A {
@Id int id;

@OneToOne
B b;
}

@Entity
class B {
@Id int id;

@OneToOne(mappedBy="b")
A a;
}

A是拥有方

@Entity
class A {
@Id int id;

@OneToOne(mappedBy="a")
B b;
}

@Entity
class B {
@Id int id;

@OneToOne
A a;
}

在“普通 SQL”中考虑这一点,我认为这与拥有两个表,每个表都有另一个表的外键是一样的。我不明白的是指定哪个实体是拥有方的效果是什么,即使用“mappedBy”属性。这实际上实现了什么,因为我不相信普通 SQL 中有等效项。

最佳答案

JPA 2.0 specification ,第 2.9 节写道:

Relationships may be bidirectional or unidirectional. A bidirectional relationship has both an owning side and an inverse (non-owning) side. A unidirectional relationship has only an owning side. The owning side of a relationship determines the updates to the relationship in the database, as described in section 3.2.4.

The following rules apply to bidirectional relationships:

  • The inverse side of a bidirectional relationship must refer to its owning side by use of the mappedBy element of the OneToOne, OneToMany, or ManyToMany annotation. The mappedBy element designates the property or field in the entity that is the owner of the relationship.
  • The many side of one-to-many / many-to-one bidirectional relationships must be the owning side, hence the mappedBy element cannot be specified on the ManyToOne annotation.
  • For one-to-one bidirectional relationships, the owning side corresponds to the side that contains the corresponding foreign key.
  • For many-to-many bidirectional relationships either side may be the owning side.

3.2.4节的相关部分是:

The state of persistent entities is synchronized to the database at transaction commit. This synchronization involving writing to the database any updates to persistent entities and their relationships as specified above.

Bidirectional relationships between managed entities will be persisted based on references held by the owning side of the relationship. It is the developer’s responsibility to keep the in-memory references held on the owning side and those held on the inverse side consistent with each other when they change. In the case of unidirectional one-to-one and one-to-many relationships, it is the developer’s responsibility to insure that the semantics of the relationships are adhered to.

It is particularly important to ensure that changes to the inverse side of a relationship result in appropriate updates on the owning side, so as to ensure the changes are not lost when they are synchronized to the database.

关于java - JPA - 使用 mappedBy 属性定义拥有实体的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10968536/

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