我的数据库包含3个表:person
,document
和peson_document
。 Person和Document具有多对多关系,并与包含添加列的person_document
表连接。
这是我的映射:
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;
}
在我的代码中,我正在尝试保存这样的实体:
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);
问题是hibernate没有保存它并抛出异常:insert or update on table violates foreign key constraint
- 因为在document
表中没有记录。那么为什么hibernate在保存document
之前不会持久person_document
以及如何解决这个问题呢?
答案 0 :(得分:3)
试试这个:
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