0

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

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Yuri
  • 447
  • 3
  • 9
  • 19
  • 2
    I'd help you, but the last time I did and provided an answer, instead of accepting it, upvoting it, or even just say thanks, you deleted your question. – JB Nizet Apr 12 '15 at 17:08
  • thank you so much but my problem isn't the same this time . when I tried your solution , nothing was inserted into my group_user table . – Yuri Apr 12 '15 at 17:10
  • Then you should ask for clarifications, or at least mention the problem. Not just delete the question. Anyway, regarding this question, no, saving all the users again is obviously not what you want, so yes, it's a problem. And read the javadoc of ManyToMany.cascade. What do you thing cascade = ALL means? – JB Nizet Apr 12 '15 at 17:14
  • thanks , changing the cascade ALL to cascade = {CascadeType.PERSIST, CascadeType.MERGE} solved the removing problem . Is there any other solution to not save all the users again – Yuri Apr 12 '15 at 17:37

0 Answers0