Search code examples
javahibernategrailsjpagrails-orm

Not able to update my newly added item in collection to database using grails and JPA


I am facing issue in updating one of my domain(Library) in grails for long time,am trying to update my library after adding a new book to it but the added book is not getting saved.

I have mapping of bookCollection in my domain Class Library as below:

@OneToMany(cascade = CascadeType.ALL, mappedBy = "Library")
    Collection<Book> bookCollection;


I am trying to add a new book to my Library(Initially there is no book in  bookColletion):

Library library = Library.get(1)
Book book=Book.get(1)
library.bookCollection.add(book)

and update it:
library.save(flush:true,failOnError: true)

Library is got saved but  my book is not.

I am using grails and JPA.

Thanks


Solution

  • You don't set the other side of the relation: the library of the book.

    Library library = Library.get(1)
    Book book=Book.get(1)
    library.bookCollection.add(book)
    book.library = library; // <--- sets the other side of the relation