gpt4 book ai didi

java - 映射带有额外列的@ManyToMany 关联表

转载 作者:行者123 更新时间:2023-11-29 04:31:40 24 4
gpt4 key购买 nike

我的数据库包含 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 在保存 person_document 之前不保留 document 以及如何解决这个问题?

最佳答案

试试这个:

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

关于java - 映射带有额外列的@ManyToMany 关联表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43547779/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com