0

Using the classic author/book pattern (grails 2.2.0).

class Author { static hasMany = [books: Book] } class Book { static belongsTo = [author: Author] } 

Why when I create a child instance it dosent update the parent set:

Author author = new Author().save() Book book = new Book(author: author).save() assert author.books.size == 1 // FAIL 

As the author object wont change in the database, why do I have to use author.addToBooks(book).save() ???

1 Answer 1

4

Per Grails addTo documentation,

In addition, calling addTo* initializes the associated collections, and sets the back-reference of the author property in each Book.

addTo explicitly adds the association in the collection and the back reference. In your example, you are only adding the back-reference, but never the association in the collection. Basically cascading association is only perform from owner to dependent. If you think about this it makes sense because what happens if you have something like the following:

class Author { static hasMany = [fictionBooks: Book, nonFictionBooks: Book] } 

then which collection should your new Book(author: author).save() save to?

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.