【问题标题】:OneToMany column not updating on creating enteriesOneToMany 列在创建条目时未更新
【发布时间】:2020-05-28 04:13:49
【问题描述】:

我有两个实体/表

为简洁起见删除了一些列

组:

@Entity
@Table(name = "groups", indexes = {@Index(name = "groups_index", columnList = "id", unique = true)})
public class Group implements Serializable {

    @OneToMany(targetEntity = UserInGroup.class, mappedBy = "group")
    private Set<UserInGroup> userInGroups = new HashSet<>();

}

UserInGroup:


@Entity
@Table(name = "user_in_group", indexes = {@Index(name = "user_in_group_index", columnList = "group_id,user_id", unique = true)})
public class UserInGroup implements Serializable {

    @ManyToOne
    @JoinColumn(name = "group_id", referencedColumnName = "id")
    private Group group;

}

我参考了这些链接123。 我已经完成了他们概述的内容

现在我在 UserInGroup 表中创建了一个条目,但 group 实体并没有使用 UserInGroup 中的新条目进行更新强>表。

群组未更新

在 UserInGroups 中创建的条目

在群组中创建的条目


编辑:

基于这个answer我添加了以下内容

UserInGroup userInGroup = new UserInGroup().setGroup(group).setUser(creatorUser).setGroupRoleEnum(GroupRoleEnum.ADMIN);
group.addUserInGroup(userInGroup);
groupRepository.save(group);
public void addUserInGroup(UserInGroup userInGroup) {
    if (userInGroups == null) {
        userInGroups = new ArrayList<>();
    }
    userInGroups.add(userInGroup);
    userInGroup.setGroup(this);
}

但表 UserInGroup 仍然没有创建任何条目。

【问题讨论】:

    标签: java spring jpa


    【解决方案1】:

    在您的代码中,在您的双向关系中,您使用mappedBy 属性将Group 实体标记为关系的拥有方。因此,如果您使用GroupRepository 实例来传播GroupUserInGroup 值,那么一切都应该正常运行。这不是在UserInGroupRepository 实例上调用保存,而是使用GroupRepository 实例来保存值和外键关联应该自动创建。使用addUserInGroup(userInGroup)removeUserInGroup() 方法向Group 类中的集合添加或删除值。

    groupRepository.save(group);
    

    更多信息相关帖子:Springboot add problem in oneTOMany relation

    【讨论】:

    • 我按照您的建议进行了更改。但groupRepository 不保存UserInGroup 实体。
    猜你喜欢
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 2017-12-02
    • 2021-05-20
    • 1970-01-01
    • 2017-09-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多