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

I am having trouble understanding the difference between declaring an object domain in another domain and indicating the relationship between the domains.

Code example:

class User { Book book } 

vs

 class User { static hasOne = Book } class Book { String name } 
+4
source share
2 answers

The hasOne relationship puts the key in the child, so in db you will find book.user_id with hasOne, rather than user.book_id if you just declare the Book book for the user. You will see the difference in DDL generation if you use grails schema-export .

Here is the DDL with hasOne in place:

 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; 

Here is the DDL with just a Book book on the user:

 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; 

Note that the book table has a link in the first example, and the user has it in the second.

Long answer: I highly recommend watching Burt Beckwith's presentation at GORM / collections / mapping. A lot of great information about GORM and the consequences of various advantages / problems with the description of relations with hasMany / belongs to, etc.

+3
source

The main difference is that when hasOne is used, the foreign key reference is stored in the child table instead of the parent table, that is, the user_id column will be stored in the book table instead of the book_id column that is stored in the user table. If you have not used hasOne, then the column book_id will be generated in the user table.

The Grails documentation for hasOne has an explanation and an example.

Hope this helps.

+1
source

Source: https://habr.com/ru/post/1343505/


All Articles