【问题标题】:Grails / Gorm : Difference between declaring object and describing relationship?Grails / Gorm:声明对象和描述关系之间的区别?
【发布时间】:2011-03-13 03:27:13
【问题描述】:

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

示例代码:

class User { 
Book book
}

对比

class User { 
static hasOne = Book
}

class Book {
String name
}

【问题讨论】:

  • 图书类在两种情况下都保持不变

标签: grails grails-orm grails-domain-class


【解决方案1】:

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 等关系的各种优势/问题的后果。

【讨论】:

  • 嗨泰德,非常感谢分享知识和视频!在提出问题之前进行研究时(我什至在多个查询中访问了第 5 页的谷歌结果。)我实际上看到了这个视频,但很快就将其驳回。仅仅看了前 15 分钟后,我觉得我学到了很多我需要知道的东西,而我所拥有的书中没有涵盖这些东西。我显然是 grails 的新手,但对关系数据库有很好的背景,这是我第一次没有真正编写 sql,所以我对效率感到非常不安。再次感谢!
  • 很好,谢谢。只是一个建议,在答案中保持示例的顺序(如问题中所要求的那样)将有助于阅读。 :)
【解决方案2】:

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

Grails documentation for hasOne中有解释和例子。

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-20
    相关资源
    最近更新 更多