[英]Bidirectional OneToMany vs OneToOne association with mappedBy attribute
I defined entities with @OneToOne bidirectional relationship.我定义了具有@OneToOne双向关系的实体。
Owner site of relationship ( Child class):所有者关系站点(子类):
@OneToOne
@JoinColumn(name = "owner_id")
private Parent parent;
Other site ( Parent class):其他站点(父类):
@OneToOne(mappedBy = "parent")
private Child child;
When I try to persist Parent who has child set (which is not persisted) then I got exception当我尝试坚持拥有子集的父母(未坚持)时,我遇到了异常
which looks understandable.这看起来可以理解。
But when I defined entities with bidirectional OneToMany/ManyToOne association like:但是,当我定义具有双向 OneToMany/ManyToOne 关联的实体时,例如:
The owning site of this relationship:此关系的拥有站点:
@ManyToOne
@JoinColumn(name = "owner_id")
private Parent parent;
The other side of the relationship:关系的另一端:
@OneToMany(mappedBy = "parent")
private Set<Child> childrens = new HashSet<>();
and try to persist Parent who has children collection set (which are not persisted) then I can do it and Hibernate persist only Parent.并尝试坚持拥有子集合集(未坚持)的父母,然后我可以做到,而 Hibernate 只坚持父母。
For me it looks strange because this behavior is not deterministic - I know that this example is not correctly and I can use CascadeType.ALL or persist it correctly.对我来说,这看起来很奇怪,因为这种行为不是确定性的——我知道这个例子不正确,我可以使用CascadeType.ALL或正确地坚持它。 Do you know why it looks that?你知道为什么它看起来像吗? Is that Hibernate use different algorithms to persist entities in @OneToOne/@OneToMany relationship Hibernate 是否使用不同的算法来保持@OneToOne/@OneToMany 关系中的实体
If you use cascade = PERSIST
on the @OneToMany
you should see the same error.如果您在 @OneToMany 上使用cascade = PERSIST
@OneToMany
您应该会看到相同的错误。 The difference is just that Hibernate does not try to "manage" *-to-many associations on the inverse side ie where the mappedBy
is present.不同之处在于 Hibernate 不会尝试“管理”反面的 * 对多关联,即存在mappedBy
的地方。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.