java - 为什么我会收到唯一索引或主键违规?
问题描述
我正在尝试使用 Spring MVC 在两个人之间添加友谊关系。第一个调用顺利,但第二个调用抛出唯一索引或主键违规?,为什么我得到它?
@Entity
@Table(name="PERSON")
public class Person {
@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
private Long id;
@ManyToMany(fetch = FetchType.EAGER)
@ElementCollection
private List<Person> friends;
@ManyToMany(mappedBy="friends", fetch = FetchType.EAGER)
@ElementCollection
private List<Person> friendOf;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public List<Person> getFriends() {
return friends;
}
public void setFriends(List<Person> friends) {
this.friends = friends;
}
public List<Person> getFriendOf() {
return friendOf;
}
public void setFriendOf(List<Person> friendOf) {
this.friendOf = friendOf;
}
public void addFriend(Person person){
if(this.getFriends() == null){
this.friends = new ArrayList<>();
}
this.friends.add(person);
}
public void setFriendship(Long firstPersonId, Long scndPersonId){
Person firstPerson = personService.getPerson(firstPersonId);
firstPerson.addFriend(personService.getPerson(scndPersonId));
personService.savePerson(firstPerson);
Person scndPerson = personService.getPerson(scndPersonId);
scndPerson.addFriend(personService.getPerson(firstPersonId));
personService.savePerson(scndPerson);
}
Person pup1 = new Person();
Long pupId1 = controller.savePerson(pup1);
Person pup2 = new Person();
long pupId2 = controller.savePerson(pup2);
setFriendship(pupId1, pupId2);
Person pup3 = new Person();
long pupId3 = controller.savePerson(pup3)
controller.setFriendship(pupId3, pupId1); //This throws an exception
controller.setFriendship(pupId3, pupId2);
为什么标记的行会导致异常?p1 和 p2 之间对 setFrienship 的第一次调用成功,但是当我尝试在 p1 和 p3 之间建立连接时,它失败并出现以下异常:
org.h2.jdbc.JdbcSQLIntegrityConstraintViolationException: Unique index or primary key violation: "PUBLIC.UK_6VEJRSUXRONFC95I7O5XJNRMU_INDEX_D ON PUBLIC.PERSON_FRIENDS(FRIENDS_ID) VALUES 2
解决方案
您需要直接指定连接和反向连接列。请注意,它们在集合中交换。
@ManyToMany
@JoinTable(name="friends",
joinColumns=@JoinColumn(name="personId"),
inverseJoinColumns=@JoinColumn(name="friendId")
)
private List<User> friends;
@ManyToMany
@JoinTable(name="friends",
joinColumns=@JoinColumn(name="friendId"),
inverseJoinColumns=@JoinColumn(name="personId")
)
private List<User> friendOf;
推荐阅读
- jsf - 编辑单元格后我无法更新 p:dataTable
- sql - Excel VBA SQL UNION SUM 对具有不同列名的表进行 GROUP BY
- tfs - TFS_Datawarehouse - 接受标准报告
- c# - ListView IsSelected 状态上的 WPF Textwrapping 触发器
- python - 模板视图中的 Django 文件下载传递值
- python - Python时间本地时间到gmtime转换问题
- python - 搜索结果不显示为抓取
- python-3.x - 使用 pandas 和 matplotlib 绘制时间序列数据框并标记某些点
- java - 如何使用没有随机数的百分比?
- angular - Angular 中的模板字符串:如何绑定函数?