0

I have two entities/tables

Removed some columns for brevity

Group:

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

}

I have referred to these links 1, 2 and 3. I have done what they have outlined

Now I make an entry in the UserInGroup table, and still, the group entity doesn't get updated with the new entries made in UserInGroup table.

Creating entry in **UserInGroup**

Group is not updated

UserInGroups is still empty

Entry Created in UserInGroups Entry Created in UserInGroups

Entry created in Groups

Entry created in Groups


Edit:

Based on this answer I added the following

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);
}

But the table UserInGroup still has no entries created.

1 Answers1

0

Well in your code, in your bi-directional relationship , you marked the Group entity as the owning side of the relation using the mappedBy attribute. So, if you use the GroupRepository instance to propagate both Group as well as the UserInGroup values, everything should workout fine.That is instead of calling save on UserInGroupRepository instance use the GroupRepository instance to save the values and the foreign key association should be created automatically. Use addUserInGroup(userInGroup) and removeUserInGroup() methods to add or remove values to the set in Group class.

groupRepository.save(group);

Related post for more information : Springboot add problem in oneTOMany relation

Ananthapadmanabhan
  • 5,706
  • 6
  • 22
  • 39