gpt4 book ai didi

Grails/Gorm : Difference between declaring object and describing relationship?

转载 作者:行者123 更新时间:2023-12-01 01:30:10 25 4
gpt4 key购买 nike

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

示例代码:

class User { 
Book book
}

相对
class User { 
static hasOne = Book
}

class Book {
String name
}

最佳答案

hasOne关系会将键放在子对象上,所以在数据库中你会发现 book.user_id使用 hasOne 而不是 user.book_id如果你只是声明 Book book在用户上。如果您使用 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 表在第一个示例中具有引用,而用户在第二个示例中具有它。

长答案:强烈推荐观看 Burt Beckwith's presentation在 GORM/集合/映射上。关于 GORM 的许多重要信息以及描述与 hasMany/belongsTo 等关系的各种优势/问题的后果。

关于Grails/Gorm : Difference between declaring object and describing relationship?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5287201/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com