【问题标题】:generated Jointable is not updated in manytomany mapping while updating the entity更新实体时,生成的 Jointable 不会在多对多映射中更新
【发布时间】:2019-08-19 10:28:38
【问题描述】:

我有两个实体,一个是用户,另一个是角色。 用户到角色是双向多对多映射。 我已经用一些预定义的角色填充了我的数据库(postgres)。

用户表如下所示

@Entity(name = "user_identity")
public class UserIdentity {
@Column(name = "user_identity_id", nullable = false, unique = true, 
updatable = false)
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy =  
"org.hibernate.id.UUIDGenerator")
@Id()
@JsonProperty("userIdentityId")
private String userIdentityId = null;

@ManyToMany(targetEntity= Role.class, fetch = FetchType.EAGER, cascade = 
{CascadeType.PERSIST, CascadeType.MERGE})
@JoinTable(name = "user_identity_roles", joinColumns = {
        @JoinColumn(name = "user_id", referencedColumnName = 
"user_identity_id") }, inverseJoinColumns = {
                @JoinColumn(name = "role_id", 
referencedColumnName = "id") })
private List<Role> roles = new ArrayList<Role>();



/**
 * Returns the value of '<em><b>roles</b></em>' feature.
 *
 * <!-- begin-user-doc --> <!-- end-user-doc -->
 * 
 * @return the value of '<em><b>roles</b></em>' feature
 */
public List<Role> getRoles() {
    return roles;
}

/**
 * Sets the '{@link UserIdentity#getRoles() <em>roles</em>}' feature.
 *
 * <!-- begin-user-doc --> <!-- end-user-doc -->
 * 
 * @param newRoles the new value of the '{@link UserIdentity#getRoles() roles}'
 *                 feature.
 */
public void addRole(Role newRole) {
    this.roles.add(newRole);
    newRole.getUsers().add(this);
}
}

角色表如下所示

public class Role{

@Id()
@Column(name = "id", nullable = false, unique = true, updatable = 
false)
@GeneratedValue(generator = "UUID")
@GenericGenerator(name = "UUID", strategy ="org.hibernate.id.UUIDGenerator")
private String id = null;


@ManyToMany(mappedBy = "roles",, cascade = {CascadeType.PERSIST, CascadeType.MERGE}, fetch = FetchType.LAZY)
@JsonIgnore 
private List<UserIdentity> users = new ArrayList<UserIdentity>();



public List<UserIdentity> getUsers() {
    return users;
}


public void addUsers(UserIdentity newUser) {
    this.users.add(newUser);
}
}

在创建具有角色的用户时,user_identity_roles 表(Join 表)会使用 userId 和 roleId 进行更新。

无法使用新角色更新现有用户。 下面是用新角色更新现有用户的代码。

@Transactional(propagation = Propagation.REQUIRED)
public boolean updateRoleOfUser(String userId, String roleId) {

    if (Strings.isNullOrEmpty(roleId) || Strings.isNullOrEmpty(userId)) {
        return false;
    }

    Optional<UserIdentity> existingUser = userRepository.findById(userId);

    if (!existingUser.isPresent()) {
        throw new ResourceNotFoundException(userId, "User not found with this id");
    }

    UserIdentity oldUser = existingUser.get();

    Optional<Role> roleById = roleRepository.findById(roleId);

    if (!roleById.isPresent()) {
        throw new ResourceNotFoundException(roleId, "role not found with this id");
    }

    Role role = roleById.get();

    oldUser.getRoles().add(role);
    UserIdentity newUserIdentity = userRepository.save(oldUser);

    role.getUsers().add(newUserIdentity);

    return newUserIdentity != null;
}

我已经尝试使用 Set 而不是 List。 我正在使用弹簧数据 JpaRepository。

我的预期输出是将新角色 ID 保存到生成的可连接中。 在这个问题上提供一些指示会非常有帮助

【问题讨论】:

    标签: spring-boot spring-data-jpa spring-data many-to-many


    【解决方案1】:

    您必须在保存之前进行双向映射。必须将角色添加到用户,并且必须将用户添加到角色。之后可以触发保存。目前您正在将角色添加到用户,保存然后将用户添加到角色。

    编辑: 或者使用已经定义好的方法 oldUser.addRole(role) 已经做了双向映射。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-17
      • 2021-02-21
      • 2015-09-02
      • 1970-01-01
      • 1970-01-01
      • 2023-01-21
      • 1970-01-01
      • 2019-01-23
      相关资源
      最近更新 更多