将@ManyToMany关联表与额外列映射
我的数据库包含3个表: person
, document
和peson_document
。 Person和Document具有多对多关系,并与包含添加列的person_document
表连接。 这是我的映射:
class Person { @Cascade(CascadeType.ALL) @OneToMany(mappedBy = "compositePK.person", orphanRemoval = true) Set personDocuments; } class Document { @OneToMany(mappedBy = "compositePK.document") Set 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 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不保存它并抛出exception: insert or update on table violates foreign key constraint
– 因为在document
表中没有记录。 那么为什么hibernate在保存person_document
之前不会保留document
以及如何解决这个问题呢?
尝试这个:
public class Person { @OneToMany(mappedBy = "person", orphanRemoval = true, cascade= CascadeType.ALL) Set personDocuments; }
class Document { @OneToMany(mappedBy = "document") Set 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