简体   繁体   English

唯一约束 - 密钥已存在于多对多中

[英]Unique constraint - Key already exists in many to many

I have the classic many-to-many relationship between my users and their roles. 我的用户和他们的角色之间存在经典的多对多关系。 It saves the first user correctly, but then when I try to insert the second user it gives me an unique key violation with (role_id)=(56) already exist... 它正确地保存了第一个用户,但是当我尝试插入第二个用户时,它给了我一个唯一的密钥违例(role_id)=(56)已经存在...

I already tried many variations of fetching types. 我已经尝试了许多提取类型的变体。 I am using Spring crud repositories. 我正在使用Spring crud存储库。

My user: 我的用户:

@ManyToMany
@JoinTable(
        name = "user_role",
        joinColumns = @JoinColumn(name = "userId"),
        inverseJoinColumns = @JoinColumn(name = "roleId")
)
private Set<Role> roles;

public void addRole(Role role) {
    if (roles == null) {
        this.roles = new HashSet<>();
    }
    this.roles.add(role);
    role.getUsers().add(this);
}

public void removeRole(Role role) {
    this.roles.remove(role);
    role.getUsers().remove(this);
}

My roles: 我的角色:

@ManyToMany(mappedBy = "roles", fetch = FetchType.EAGER)
Set<User> users;

public Role(Roles role) {
    this.role = role.getRole();
    this.users = new HashSet<>();
}

My database populating code: 我的数据库填充代码:

Role userRole = roleService.createIfNotExist(Roles.ROLE_USER);

//Role userRole = new Role(Roles.ROLE_USER);
user.addRole(userRole);

//roleRepository.save(userRole);
User result = userRepository.save(user);

If I create a new user role with new Role etc as shown in the commented out code everything works fine but I get duplicate roles saved to the data base. 如果我使用新的Role等创建一个新的用户角色,如注释掉的代码所示,一切正常,但我将重复的角色保存到数据库中。

您可以使用merge而不是persist,因为如果实体存在,它将更新它,否则插入它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM