所以我有两个表:Person(id,age,firstname,lastname) 和 Knows(person_id,other_person_id,creationDate),为了映射这些表,我创建了两个代表 Knows、Person 实体的类和 Knows 中的一个可嵌入类(为了表示复合主键,其中包含两列:person_id 和 other_person_id)。 在我的 Person.java 类中,我使用了下一个映射注释:
@ManyToMany(cascade=CascadeType.PERSIST)
@JoinTable(
name="knows",
joinColumns = {@JoinColumn(name="person_id")},
inverseJoinColumns = {@JoinColumn(name= "other_person_id")}
)
protected Set<Knows>knowsSet=new HashSet<Knows>();
@OneToMany(mappedBy = "person")
protected Set<Knows>personsSet=new HashSet<Knows>();
@OneToMany(mappedBy = "other_person")
protected Set<Knows>other_personsSet=new HashSet<Knows>();
这里是 Knows.java 类中的注解:
@Entity(name = "Knows")
@Table(name = "knows",schema = "socialnetwork")
public class Knows {
public Knows() {
}
@Embeddable
public static class Id implements Serializable {
@Column(name="person_id")
protected long personId;
@Column(name="other_person_id")
protected long otherPersonId;
public Id() {
}
public Id(long personId,long otherPersonId) {
this.personId = personId;
this.otherPersonId = otherPersonId;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Id id)) return false;
return personId == id.personId && otherPersonId == id.otherPersonId;
}
@Override
public int hashCode() {
return Objects.hash(personId,otherPersonId);
}
}
@EmbeddedId
protected Id id=new Id();
@Column(name = "creation_date")
private String creation_date;
@ManyToOne
@MapsId("person_id")
private Person person;
@ManyToOne
@MapsId("other_person_id")
private Person other_person;
public String getCreation_date() {
return creation_date;
}
至于我映射是正确完成的,但每次我在调试后收到下一个异常: 以实体“org.example.entity.Knows”为目标的关联“org.example.entity.Person”有 1 个“@JoinColumn”,但主键有 2 列