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?

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top