Search code examples
grailsgrails-orm

In below relation does it one to many or many to many relation and why?


class Face {
   static hasMany = [nose:Nose]  
} 

class Nose {
}

In above code it seems to be one to many but I am able to insert data using GORM in db which is indicating many to many relationship. The mapping is unidirectional, is that the only reason the relationship is one to many?


Solution

  • This is a unidirectional one-to-many relationship. However a face_nose join table will be created by GORM, so from the point-of-view of the generated schema it looks like a many-many relationship. I assume this is what you mean by:

    which is indicating many to many relationship

    There are a variety of things you can do to make the tables look more like those of a typical one-to-many relationship, e.g. make it bidirectional

    class Face {
       static hasMany = [nose:Nose]  
    }
    
    class Nose {
        String name
        static belongsTo = [face: Face]
    }
    

    You should be aware that the above mapping will cause deletes of a Face to cascade to any associated Nose instances, which may not be what you want.