Search code examples
grailsmany-to-manygrails-orm

many-to-many in grails is not saving records in the relationship table


I've got a many-to-many association between Color and Shade. Color has many shades and Shades has many colors.

I've modeled this like so:

class Color {
  static hasMany = [shades: Shade]
  String name
}

class Shade {
  static belongsTo = Color
  static hasMany = [colors: Color]
  String name
}

However, when I run the following code:

new Color(name: "Red").addToShades(new Shade(name: "light")).save()

It only saves record in Color table and Shade table but not in Color_Shades table which is essentially a join table between the two.

Am I doing something wrong? Thats how I understood it from the docs:


Solution

  • I'm not sure why your table isn't populated, but there's an advise of Burt in this talk about the performance using this type of many-to-many. The solution is to use an intermediate class:

    class ColorShade implements Serializable {
    
      Color color
    
      Shade shade
    
      //implement hashcode & equals!
      //and also implement helpers like removeAll, remove, create and get.
    
      static mapping = {
        id composite: ['color','shade']
        table 'Color_Shades'
        version false
      }
    }
    

    You can see a example class in the Spring Security Core plugin.