Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

grails

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.

like image 935
Steve Kuo Avatar asked Nov 06 '22 19:11

Steve Kuo


1 Answers

You need to manually flush the hibernate session like this:

person.save(flush:true)
like image 96
Lloyd Meinholz Avatar answered Nov 15 '22 05:11

Lloyd Meinholz