如何在grails中建立一对一的双向关系?
我有两个域类,并且希望它们之间具有一对一的双向关系。我写道:
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
那么这意味着它不是双向的?怎么做成双向的?
I have two domain classes and want to have one-to-one BIDIRECTIONAL relation between them. I write:
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
}
So, i want to have bi-directional, i could NOT find link from Book to Person in generated SQL:
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
So then it means it is not bidirectional then? How to make bidirectional?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
检查 hasOne 属性,在哪个类中定义 hasOne 和 BelongsTo 取决于您希望存储 FK 的位置,检查有关 hasOne 的 grails 文档:
http://www.grails.org/doc/latest/参考/Domain%20Classes/hasOne.html
check out the hasOne property, in which class you define hasOne and belongsTo depends on where you want the FK to be stored, check this grails doc regarding hasOne:
http://www.grails.org/doc/latest/ref/Domain%20Classes/hasOne.html
要使这种关系成为一对一的双向关系,您应该将它们定义为fallows
ownTo 用于指定一对多、多对一或多对多关系的所有者方(管理关系),并且为了建立双向关系,
belongsTo 应该始终在拥有方使用
To make this relationship one to one bidirectional,you should define them as fallows
belongsTo is used for specifying the owner side(which manages relationship) of a one-to-many, many-to-one, or many-to-many relationship and for making relationship bidirectional
belongsTo should be used always in owned side