Search code examples
jquerygrailsmany-to-manygsp

Many-to-many GSP persistance


I have a many-to-many relationship between employee and position. Can someone show me how to implement adding positions to employees? Controller and GSP to. I want to implement this on create and update emloyee GSPs. On employee create.gsp I want to have textfield for entering employee name, and combobox with existing positions. Also I want to have Add Position button which will render another combobox for adding more positions. For me as an absolute begginer this is not that obvious and there aren't many examples concerning this. It would be greate to have a concrete example.


Solution

  • Honestly, stackoverflow is for q&a, not "make this for me".

    Your question on how to map many-to-many is valid though, and one very common way is to simply have a join table holding both relationships.

    Example you can reverse engineer to fit your classes is the UserRole class from spring-security-core.

    class UserRole implements Serializable {
    
    User user
    Role role
    
    
    static UserRole get(long userId, long roleId) {
        find 'from UserRole where user.id=:userId and role.id=:roleId',
            [userId: userId, roleId: roleId]
    }
    
    static UserRole create(User user, Role role, boolean flush = false) {
        new UserRole(user: user, role: role).save(flush: flush, insert: true)
    }
    
    static boolean remove(User user, Role role, boolean flush = false) {
        UserRole instance = UserRole.findByUserAndRole(user, role)
        if (!instance) {
            return false
        }
    
        instance.delete(flush: flush)
        true
    }
    
    static void removeAll(User user) {
        executeUpdate 'DELETE FROM UserRole WHERE user=:user', [user: user]
    }
    
    static void removeAll(Role role) {
        executeUpdate 'DELETE FROM UserRole WHERE role=:role', [role: role]
    }
    
    static mapping = {
        id composite: ['role', 'user']
        version false
    }
    }
    

    Some auxilliary stuff removed, like the hashcodes and clones etc.

    The basic idea is to have a join table that holds the id of both your classes.