Saturday, November 7, 2009

Grails 1.1, integration tests, and unsaved transient instance errors

In the grails documentation, and every book on the subject you will find an example similar to:

class Author {
    static hasMany = [ books : Book ]
    String name

class Book {
  static belongsTo = Author
  Author author
  String title

The belongsTo reference ensures that saves, updates, and deletes are cascaded. All the information that I have found provides an example to save your domain classes like:

new Author(..)
       .addToBooks(new Book(..))

During recent development, I was creating an integration test on a model very similar to this and kept seeing errors that stated "object references an unsaved transient instance -  save the transient instance before flushing". Pouring over my code, everything looked correct - all the relationships were correctly defined, it was simply refusing to save properly. In the end I got lucky with a google search and found that there is a bug in 1.1 that only affects integration tests (and is fixed in 1.2RC1). If you update your save to:

new Author(..)
       .addToBooks(new Book(..))
       .save(flush:true, validate:false)

the save will cascade correctly.

No comments:

Post a Comment