4

我无法理解在另一个域中声明域对象和指定域之间的关系之间的区别。

示例代码:

class User { 
Book book
}

相对

class User { 
static hasOne = Book
}

class Book {
String name
}
4

2 回答 2

3

hasOne关系会将键放在子对象上,因此在数据库中您会发现book.user_idhasOne 而不是user.book_idBook book在 User 上声明。如果您使用grails schema-export.

这是使用 hasOne 的 DDL:

create table book (id bigint generated by default as identity (start with 1), version bigint not null, user_id bigint not null, primary key (id), unique (user_id));
create table user (id bigint generated by default as identity (start with 1), version bigint not null, primary key (id));
alter table book add constraint FK2E3AE98896CD4A foreign key (user_id) references user;

Book book这是仅在用户上的 DDL :

create table book (id bigint generated by default as identity (start with 1), version bigint not null, primary key (id));
create table user (id bigint generated by default as identity (start with 1), version bigint not null, book_id bigint not null, primary key (id));
alter table user add constraint FK36EBCB952E108A foreign key (book_id) references book;

请注意,书表在第一个示例中具有参考,而用户在第二个示例中具有参考。

长答案:我强烈推荐观看Burt Beckwith关于 GORM/collections/mapping 的演讲。很多关于 GORM 的重要信息以及描述与 hasMany/belongsTo 等关系的各种优势/问题的后果。

于 2011-03-13T05:01:14.840 回答
1

主要区别在于,当使用 hasOne 时,外键引用存储在子表而不是父表中,即 user_id 列将存储在 book 表中,而不是将 book_id 列存储在 user 表中。如果您没有使用 hasOne,则会在 user 表中生成 book_id 列。

Grails 文档中有对 hasOne的解释和示例。

希望这可以帮助。

于 2011-03-13T05:01:18.750 回答