Grails的Many-to-Many改良

标准的M-M做法:
class User{
    static hasMany=[roles:Role]
    String name
}

class Role{
    static belongsTo = User
    static hasMany=[users:User]
    String name
}

使用方法:
Role roleUser=new Role(name: "ROLE_USER").save()
Role roleAdmin==new Role(name: "ROLE_ADMIN").save()

User user1= new User(name: "bruce_lin_chn")
user1.addToRoles(roleUser)
user1.save()

存在的问题:
[list]
  • hasMany会在User和Role中创建Set(org.hibernate.collection.PersistentSet)
  • 为了唯一性检查,增加一个Role到User要求加载所有用户角色的实例和所有其他拥有该权限的用户
  • 存在乐观锁异常的风险
  • 解决方案:
    class User{
        String name
    }
    
    class Role{
        String name
    }
    
    class UserRole implements Serializable{
        User user
        Role role
        static mapping = {
            table 'user_role_mapping'
            version false
            id composite: ['user', 'role']
        }
        
        static Set<Role> getRoles(User user){
            UserRole.findAllByUser(user).collect{it.role} as Set
        }
    
        static boolean hasRole(User user, Role role){
            return UserRole.countByUserAndRole(user,role)>0
        }
    
        static beforeDeleteUser(User user){
            
        }
    
        static beforeDeleteRole(Role role){
    
        }
    }
    


    你可能感兴趣的:(Hibernate,grails)