将@ManyToMany关联表与额外列映射

时间:2017-04-21 16:31:19

标签: java hibernate jpa mapping

我的数据库包含3个表:persondocumentpeson_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以及如何解决这个问题呢?

1 个答案:

答案 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