Grails save() doesn't save if called after relationship is added

Tag: grails Author: loveping200905 Date: 2009-09-14

I have two domain classes - Person has many Books. If I create a Person, call save(), then create+add Books to the Person, everything is persisted to the database. If I create a Person, then create+add Books, followed by save(), nothing get persisted.

Example code:

class Person {
   ...
   static hasMany = [books: Book]
}

class Book {
   ...
   static belongsTo = [person: Person]
}

Works, saves to database:

def person = new Person(...).save()
def book = new Book(...)
person.addToBooks(book)

Doesn't not work, doesn't save to database:

def person = new Person(...)
def book = new Book(...)
person.addToBooks(book)
person.save()

Why is this?

I'm running this from the Groovy console. I've tried calling ctx.sessionFactory.currentSession.clear() which doesn't help.

Resolved: The Book I was attaching to the Person had errors in it. By calling person.hasErrors() and getErrors() I was able to see that my Book was failing validation. This was being run from the Grails console so there wasn't any validation error messages.

Other Answer1

You need to manually flush the hibernate session like this:

person.save(flush:true)

Other Answer2

I don't know for sure but I presume it's because save() sets the ID of the Person which would be required to be able to add a Book to it's book collection.

I'd suggest doing some googling on Hibernate collection behaviour, it could be the way Hibernate works or maybe it's a bug in the version of Grails you're using.

Another thing to try is forcing a flush with person.save(flush:true)