如何在grails中建立一对一的双向关系?

时间:2010-12-25 09:37:00

标签: grails groovy gorm

我有两个域类,并希望它们之间具有一对一的双向关系。我写道:


class Person {

  Book book;

  String name
  Integer age
  Date lastVisit

  static constraints = {
    book unique: true  // "one-to-one". Without that = "Many-to-one".
  }

}
 


class Book {

  String title
  Date releaseDate
  String ISBN

  static belongsTo = [person:Person] // it makes relationship bi-directional regarding the grails-docs 
}


 

所以,我想要双向,我找不到生成的SQL中从Book到Person的链接:


CREATE TABLE `book` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `version` bigint(20) NOT NULL,
  `isbn` varchar(255) NOT NULL,
  `release_date` datetime NOT NULL,
  `title` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=latin1

那么这意味着它不是双向的吗?如何制作双向?

2 个答案:

答案 0 :(得分:3)

查看hasOne属性,您在其中定义hasOne和belongsTo的类取决于您希望存储FK的位置,请查看有关hasOne的grails文档: http://www.grails.org/doc/latest/ref/Domain%20Classes/hasOne.html

答案 1 :(得分:1)

要使这种关系一对一双向,您应该将它们定义为fallows

     //Person is the owning side of relationship
     class Person {

      //a foreign key will be stored in Book table called person_id
      static hasOne = [book:Book]

      static constraints = {
        book unique: true
      }  
    }

    Class Book{
     Person person
    }

belongsTo用于指定一对多,多对一或多对多关系的所有者方(管理关系)以及使关系双向

belongsTo应始终在自有方面使用