Hibernate ManyToMany Save, SaveOrUpdate And Delete Operations

03-05-2015

In Hibernate ManyToMany relationship, save or saveOrUpdate operations must be as follows:

User Entity

@ManyToMany(fetch = FetchType.LAZY,cascade = CascadeType.ALL)
@JoinTable(
    name = "UserRole_User",
    joinColumns = @JoinColumn(name = "userId", nullable = false, updatable = false),
    inverseJoinColumns = @JoinColumn(name = "userRoleId", nullable = false, updatable = false)
)
private List<UserRole> userRoleList=new ArrayList<UserRole>();
In Line 1, cascade provides that when user is saved, an insert operation will be executed on UserRole_User table automatically. CascadeType.ALL contains INSERT, UPDATE, DELETE, REFRESH and DETACH. If you want to only cascade INSERT statement, you can use CascadeType.PERSIST

In Line 4 and 5, userId and userRoleId are primary keys of User and UserRole entities, respectively. Also note that, userId is used in joinColumns attribute.

UserRole Entity


@ManyToMany(fetch = FetchType.LAZY, mappedBy = "userRoleList")
@JsonIgnore
private List<User> userList;

Test Class

public static void main(String[] args) {
    
    Session session = HibernateUtil.getSessionFactory().openSession();
    
    session.beginTransaction();
    
    User user = new User();
    user.setUsername("myuce");
    
    UserRole userRole=new UserRole();
    userRole.setName("ROLE_ADMIN");
    
    List<UserRole> userRoleList = new ArrayList<UserRole>();
    userRoleList.add(userRole);
    
    user.setUserRoleList(userRoleList);
    
    session.save(user);
    
    session.getTransaction().commit();
}

Result:

Hibernate: 
    insert 
    into
        User
        (username,name,surname) 
    values
        (?, ?, ?)
Hibernate: 
    update
        UserRole 
    set
        role=? 
    where
        userRoleId=?
Hibernate: 
    insert 
    into
        UserRole_User
        (userId, userRoleId) 
    values
        (?, ?)

Note: A cascade set to DELETE wouldn't delete the association between a userRole and a user when you delete a user. It would delete the groups themselves. To delete the association, you just have to remove all the groups from the collection of groups of the user before deleting the user:

   @Override
    public boolean delete(Integer entityId) {
        User entity = (User) currentSession().get(daoType, entityId);
        if (entity != null) {
            entity.getUserRoleList().clear();//clear() method must b
            currentSession().delete(entity);
            return true;
        } else {
            return false;
        }
    }

Removing the groups from the users is what will delete the associations from the join table.

© 2019 All rights reserved. Codesenior.COM