Grails Domain Class : hasOne, hasMany without belongsTo

Manazir Ahsan picture Manazir Ahsan · May 28, 2014 · Viewed 18.1k times · Source

I am new to Grails. Can I use "hasOne" or "hasMany" without using "belongsTo" to another domain-class?

Thanks in advance.

Answer

heikkim picture heikkim · May 28, 2014

Yes, you can. See examples in Grails doc: http://grails.org/doc/2.3.8/guide/GORM.html#manyToOneAndOneToOne

hasMany (without belongsTo) example from the doc:

A one-to-many relationship is when one class, example Author, has many instances of another class, example Book. With Grails you define such a relationship with the hasMany setting:

class Author {
    static hasMany = [books: Book]
    String name
}

class Book {
    String title
}

In this case we have a unidirectional one-to-many. Grails will, by default, map this kind of relationship with a join table.

hasOne (without belongsTo) example from the doc:

Example C

class Face {
    static hasOne = [nose:Nose]
}
class Nose {
    Face face
}

Note that using this property puts the foreign key on the inverse table to the previous example, so in this case the foreign key column is stored in the nose table inside a column called face_id. Also, hasOne only works with bidirectional relationships.

Finally, it's a good idea to add a unique constraint on one side of the one-to-one relationship:

class Face {
    static hasOne = [nose:Nose]
    static constraints = {
        nose unique: true
    }
}

class Nose {
    Face face
}