grails belongsTo使用

grails3 belongsTo,多对一关系

参考:http://docs.grails.org/latest/ref/Domain%20Classes/belongsTo.html

对象说明:

作者:Author

书:Book

Book 属于 Author

static belongsTo 
有两种使用方式:
方式一:
static belongsTo = Author //[Domain1,Domain2]
这种方式不存在引用,数据库不会建立索引和外键的。
感觉是没有什么用,但是在多对多中是必须要指定的,否则异常。

domain:
class Author {
    String name
    static constraints = {
    }
}
 
class Book {
    static belongsTo = Author
    String title
    static constraints = {
    }
}


数据库:




页面:





========================================================================================
方式二:
static belongsTo = [author:Author]//[doamin:Domain1,domain2:Domain2]
或者:
Author author
static belongsTo = Author

这种方式数据库Book表会建立Author的索引和外键(author_id)

doamin:

class Author {
    String name
    static constraints = {
    }
}
class Book {
    static belongsTo = [author: Author]
    String title
    static constraints = {
    }
}
数据库:
页面:
在页面中添加了author字段,可以用于book与author的关系维护。


猜你喜欢

转载自youngbrick.iteye.com/blog/2330645