首页 > 解决方案 > 为什么我会收到唯一索引或主键违规?

问题描述

我正在尝试使用 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

标签: javahibernatespring-booth2

解决方案


您需要直接指定连接和反向连接列。请注意,它们在集合中交换。

@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;

推荐阅读