hi I have a @ManyToMany
relationship (Users and Groups)
in the Group entity I have :
@ManyToMany(fetch=FetchType.EAGER , cascade = {CascadeType.PERSIST, CascadeType.MERGE})
@JoinTable(name = "group_user",
joinColumns = @JoinColumn(name = "gid"),
inverseJoinColumns = @JoinColumn(name = "uid"))
@JsonIgnore
private List<User> users;
in the User entity I have :
@ManyToMany(mappedBy = "users",fetch=FetchType.LAZY , cascade = {CascadeType.PERSIST, CascadeType.MERGE})
@JsonIgnore
private List<Group> groups;
the table "group_user" has been created . I can get the list of users in a group and the list of groups to which a user belongs using these queries :
@Query("select g From Group g join g.users u where u.id=?1")
Iterable<Group> getAllGroupsofUser(long idUser);
@Query("select u From User u join u.groups g where g.id=?1")
Iterable<User> getAllUsersingroup(long idGroup);
I want to add a user to a group so I did this
User user=userRepository.findOne(1);
Group group=groupRepository.findOne(3);
group.getUsers().add(user);
groupRepository.save(group);
this works . it adds a new line in my table group_user. Actually it insert all the new list of users ( it's a problem ) How to fix that ?
Also I need to do the same when I change fetch=FetchType.EAGER
to fetch=FetchType.LAZY
in my Group entity .
I'm still waiting for an answer ! I need a better solution for adding a user to a group without having to insert all the list again