Reputation: 1317
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?
Upvotes: 1
Views: 795
Reputation: 23226
Try this:
public class Person {
@OneToMany(mappedBy = "person", orphanRemoval = true, cascade= CascadeType.ALL)
Set<PersonDocument> personDocuments;
}
class Document {
@OneToMany(mappedBy = "document")
Set<PersonDocument> personDocuments;
}
public class PersonDocument {
@EmbeddedId
private CompositePK compositePK;
@MapsId("person")
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "person_origin_id")
private Person person;
@MapsId("document")
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "documents_guid")
private Document document;
@ManyToOne(fetch = FetchType.LAZY)
private Provider provider;
}
@Embeddable
public class CompositePK implements Serializable {
//these fields should have the same type as the ID field of the corresponding entities
//assuming Long but you have ommitted the ID fields
private Long person;
private Long document;
//implement equals() and hashcode() as per the JPA spec
}
//you must always set both side of the relationship
Person person = new Person();
Document document = new Document();
PersonDocument pd = new PersonDocument();
pd.setPerson(person);
pd.setDocument(document);
person.getPersonDocuments.add(pd);//assumes initialized
Upvotes: 3