hasOne 关系会将键放在子对象上,因此如果您仅在 User 上声明 Book book,则在数据库中您将找到带有 hasOne 的 book.user_id 而不是 user.book_id。如果您使用grails schema-export,您将看到生成的 DDL 的不同。
这是带有 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;
请注意,第一个示例中的 book 表具有引用,而用户在第二个示例中具有引用。
长答案:我强烈建议在 GORM/collections/mapping 上观看 Burt Beckwith's presentation。很多关于 GORM 的重要信息以及描述与 hasMany/belongsTo 等关系的各种优势/问题的后果。