You can do something like this
The Person Table will be:
@Entity
@Table(name = "person")
public class Person {
private Long id;
List<Wife> wives;
@Id
@GeneratedValue(strategy = GenerationType.AUTO, generator = "native")
@GenericGenerator(
name = "native",
strategy = "native"
)
@Column(name = "pk_id")
public final Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@OneToMany(mappedBy = "person", cascade = CascadeType.ALL, orphanRemoval = true)
public List<Wife> getWives() {
return wives;
}
public void setWives(List<Wife> wives) {
this.wives = wives;
}
}
and Wife Table:
@Entity
@Table(name = "wife")
public class Wife {
private Long id;
private List<Child> children;
private Person person;
@Id
@GeneratedValue(strategy = GenerationType.AUTO, generator = "native")
@GenericGenerator(
name = "native",
strategy = "native"
)
@Column(name = "pk_id")
public final Long getId() {
return id;
}
@OneToMany(mappedBy = "mother", cascade = CascadeType.ALL, orphanRemoval = true)
public List<Child> getChildren() {
return children;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "fk_person_id", nullable = false, foreignKey = @ForeignKey(name = "fk_person_wife"))
public Person getPerson() {
return person;
}
public void setId(Long id) {
this.id = id;
}
public void setPerson(Person person) {
this.person = person;
}
public void setChildren(List<Child> children) {
this.children = children;
}
}
and finally child entity:
@Entity
@Table(name = "child")
public class Child {
private Long id;
private Wife mother;
@Id
@GeneratedValue(strategy = GenerationType.AUTO, generator = "native")
@GenericGenerator(
name = "native",
strategy = "native"
)
@Column(name = "pk_id")
public final Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "fk_wife_id", nullable = false, foreignKey = @ForeignKey(name = "fk_wife_child"))
public Wife getMother() {
return mother;
}
public void setMother(Wife mother) {
this.mother = mother;
}
}
we need to create a repository for "person" entity. with JPA it's easy to do that. like this
public interface PersonRepository extends JpaRepository<Person, Long> { }
after creating repository, we need to use PersonRepository to persist a person object.
Child child = new Child();
Wife wife = new Wife();
wife.setChildren(List.of(child));
child.setMother(wife);
Person person = new Person();
person.setWives(List.of(wife));
wife.setPerson(person);
personRepository.save(person);