Grails Domain Class : hasOne, hasMany without belongsTo

拥有回忆 提交于 2020-01-02 03:30:09

问题


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

Thanks in advance.


回答1:


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
}



回答2:


Yes you can, but it behave differently

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

    class Book {
        String title

    }

In this case if you delete Author the books still existing and are independent.

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

 class Book {
        String title
      static belongsTo = [author: Author]
    }

In this other case if you delete the Author it will delete all the books pf that author in cascade.

Many-to-one/one-to-one: saves and deletes cascade from the owner to the dependant (the class with the belongsTo).

One-to-many: saves always cascade from the one side to the many side, but if the many side has belongsTo, then deletes also cascade in that direction.

Many-to-many: only saves cascade from the "owner" to the "dependant", not deletes.

http://grails.org/doc/2.3.x/ref/Domain%20Classes/belongsTo.html




回答3:


yes very easy like a class defintion but only specify hasMany but no need for hasOne

class Student {

String name

User userProfile

static hasMany =[files:File]
}


class User {

String uname

Student student

} 


class File {

String path 

Student student  // specify the belongs to like this no belong to 


}

Done!!



来源:https://stackoverflow.com/questions/23905638/grails-domain-class-hasone-hasmany-without-belongsto

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!