Grails / Gorm:声明对象和描述关系之间的区别?
我无法理解在另一个域中声明域对象和指定域之间的关系之间的区别。
示例代码:
class User {
Book book
}
与
class User {
static hasOne = Book
}
class Book {
String name
}
I'm having trouble understanding the difference between declaring a domain-object in another domain and specifying the relationship between the domains.
Sample code:
class User {
Book book
}
versus
class User {
static hasOne = Book
}
class Book {
String name
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
hasOne 关系会将键放在子对象上,因此在数据库中,如果您只是在 User 上声明
Book book
,您会发现带有 hasOne 的book.user_id
而不是user.book_id
。如果您使用grails schema-export
,您将看到生成的 DDL 的差异。这是带有 hasOne 的 DDL:
这是在 User 上只有
Book book
的 DDL:请注意,book 表在第一个示例中具有引用,而用户在第二个示例中具有引用。
长答案:我强烈建议观看 Burt Beckwith 在 GORM/collections/mapping 上的演示。关于 GORM 的大量重要信息以及描述与 hasMany/belongsTo 等关系的各种优点/问题的后果。
The hasOne relationship will put the key on the child object, so in the db you'll find
book.user_id
with hasOne rather thanuser.book_id
if you just declareBook book
on User. You'll see the difference in the DDL generated if you usegrails schema-export
.Here's the DDL with hasOne in place:
Here's the DDL with just
Book book
on User:Notice that the book table has the reference in the first example and the user has it in the 2nd.
Long answer: I strongly recommend watching Burt Beckwith's presentation on GORM/collections/mapping. Lots of great info around GORM and the consequences of various advantages/problems with describing relationships with hasMany/belongsTo, etc.
主要区别在于,使用 hasOne 时,外键引用存储在子表而不是父表中,即 user_id 列将存储在 book 表中,而不是 book_id 列存储在 user 表中。如果您没有使用hasOne,那么将在用户表中生成book_id列。
hasOne 的 Grails 文档中有一个解释和示例。
希望这有帮助。
The main difference is that when using hasOne the foreign key reference is stored in the child table instead of the parent table, i.e. a user_id column would be stored in the book table instead of a book_id column being stored in the user table. If you didn't use hasOne, then a book_id column would be generated in the user table.
There is an explanation and example in the Grails documentation for hasOne.
Hope this helps.