My database contains 3 tables: person
, document
and peson_document
. Person and Document have many-to-many relationship and are joined with the person_document
table which contains addition columns.
This is my mapping:
class Person {
@Cascade(CascadeType.ALL)
@OneToMany(mappedBy = "compositePK.person", orphanRemoval = true)
Set<PersonDocument> personDocuments;
}
class Document {
@OneToMany(mappedBy = "compositePK.document")
Set<PersonDocument> personDocuments;
}
class PersonDocument {
@EmbeddedId
private CompositePK compositePK;
@Column(name = "person_origin_id")
private String personID;
@ManyToOne(fetch = FetchType.LAZY)
private Provider provider;
@Embeddable
public static class CompositePK implements Serializable {
@ManyToOne(fetch = FetchType.LAZY)
private Person person;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "documents_guid")
private Document document;
}
In my code I'm trying save this entities like this:
Set<PersonDocument> pds = new HashSet<>();
Document doc = new Document();
//set doc, set person to new PersonDocument and add once on pds set.
person.getPersonDocuments().addAll(pds);
personRepository.save(person);
The problem is that hibernate doesn't save it and throws exception: insert or update on table violates foreign key constraint
- because in document
table there is no record. So why hibernate don't persist document
before saving person_document
and how solve this problem?