Hibernate Many to Many Relationship to Save only Association in Join Table

23-05-2015

If we want to save or update only association table, we shouldn't use cascade in @JoinTable side.

UserGroup Table

@Entity
public class UserGroup {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int userGroupId;

    @Size(min = 4, max = 20, groups = SizeConstraintGroup.class)
    @Column(length = 20)
    private String name;

    @ManyToMany(fetch = FetchType.LAZY)
    @JsonIgnore
    @JoinTable(
            name = "UserGroup_User",
            joinColumns = @JoinColumn(name = "userGroupId", nullable = false, updatable = false),
            inverseJoinColumns = @JoinColumn(name = "userId", nullable = false, updatable = false)
    )
    private List<User> userList=new ArrayList<User>();

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<User> getUserList() {
        return userList;
    }

    public void setUserList(List<User> userList) {
        this.userList = userList;
    }

    public int getUserGroupId() {
        return userGroupId;
    }

    public void setUserGroupId(int userGroupId) {
        this.userGroupId = userGroupId;
    }
}

User Table

@Entity
public class User {
    @ManyToMany(fetch = FetchType.LAZY,mappedBy = "userList")
    private List<UserGroup> userGroupList = new ArrayList<UserGroup>();
}

Test Class

@RequestMapping(value = "home/addUserGroup", method = RequestMethod.POST)
public ModelAndView addUserGroup(HttpServletRequest request) {
    String groupName=request.getParameter("groupName");
    String userNames=request.getParameter("userNames");
    ModelAndView modelAndView = new ModelAndView("admin/home/addUserGroup");
    if(userNames!=null && !userNames.contains(",")){
        userNames+=",";
    }
    if(userNames!=null && groupName!=null){
        UserGroup userGroup = new UserGroup();
        userGroup.setName(groupName);
        String[] userNameList = userNames.split("([,\\s]){1,}");
        List<User> userList = new ArrayList<User>();
        for (String username : userNameList) {
            User user = userService.getUser(username);
            userList.add(user);
        }
        userGroup.setUserList(userList);
        userGroupService.saveOrUpdate(userGroup);
        
        modelAndView.addObject("message", "Kullanıcı grubu başarılı bir şekilde eklendi/güncellendi");
        modelAndView.addObject("messageType", "success");
    }
    return modelAndView;
    
}

After running above code User entity will not be modified, only UserGroup entity and UserGroup_User association table will be updated.

Result


                    

© 2019 All rights reserved. Codesenior.COM