Mastering Java EE Development with WildFly
上QQ阅读APP看书,第一时间看更新

Cascade on one-to-one and one-to-many

Achieving cascade in the one-to-one and one-to-many relationships is very similar. In this paragraph, we consider the most common one-to-one bidirectional association:

@Entity
public class Info {
...
@OneToOne(mappedBy = "info",
cascade = CascadeType.ALL, orphanRemoval = true)
private InfoDetails details;
...
}
@Entity
public class InfoDetails {
@OneToOne
@JoinColumn(name = "id")
@MapsId
private Info info;
...
}

In this sample, the Info entity has the parent role while the InfoDetails has the child role.

It's important the bidirectional associations always be made on both sides. The parent has the addChild and removeChild methods to work with the children. These methods allows synchronization of both the sides of the association to avoid data corruption issues of the related objects.

In this sample, the CascadeType.ALL and orphan removal are important because the InfoDetails life cycle is strictly tied to that of its Info parent entity.