简体   繁体   中英

Grails One-to-many saving child only don't refresh parent child set

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() ???

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM