別のドメインでドメイン オブジェクトを宣言することと、ドメイン間の関係を指定することの違いを理解するのに苦労しています。
サンプルコード:
class User {
Book book
}
対
class User {
static hasOne = Book
}
class Book {
String name
}
別のドメインでドメイン オブジェクトを宣言することと、ドメイン間の関係を指定することの違いを理解するのに苦労しています。
サンプルコード:
class User {
Book book
}
対
class User {
static hasOne = Book
}
class Book {
String name
}
hasOne関係は子オブジェクトにキーを配置するため、db では、単に User で宣言するのbook.user_id
ではなく、hasOne で見つけることができます。を使用すると、生成される DDL の違いがわかります。user.book_id
Book book
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;
最初の例では book テーブルに参照があり、2 番目の例ではユーザーが参照していることに注意してください。
長い回答: Burt Beckwith のGORM/collections/mapping に関するプレゼンテーションを見ることを強くお勧めします。GORM に関する多くの優れた情報と、hasMany/belongsTo などとの関係を説明する際のさまざまな利点/問題の結果。
主な違いは、hasOne を使用すると、外部キー参照が親テーブルではなく子テーブルに格納されることです。つまり、book_id カラムが user テーブルに格納される代わりに、book テーブルに user_id カラムが格納されます。hasOne を使用しなかった場合、book_id 列が user テーブルに生成されます。
hasOneの Grails ドキュメントに説明と例があります。
お役に立てれば。