I defined entities with @OneToOne bidirectional relationship.
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:
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.
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. Do you know why it looks that? Is that Hibernate use different algorithms to persist entities in @OneToOne/@OneToMany relationship
If you use cascade = PERSIST
on the @OneToMany
you should see the same error. The difference is just that Hibernate does not try to "manage" *-to-many associations on the inverse side ie where the mappedBy
is present.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.