GORM nullables and unsaved transient instance

I have nullable one-to-many relations in Grails/GORM and started getting “object references an unsaved transient instance” exceptions from Hibernate. In the Grails forms, selecting a blank/no-selection value for the field sent params.myOtherObject.id==''. GORM then tries to create a new empty object and during the save(flush:true), it complains with the exception:

org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: MyOtherClass

This stackoverflow answer gave me the clue about params and I now remove the nullable field from params when it’s blank.

def myObject = MyClass.get(params.id)
if (null == params.myOtherObject.id || '' == params.myOtherObject.id) {
        myObject.myOtherObject = null
        params.remove('myOtherObject')
        }
myObject.properties = params
if (!myObject.hasErrors() && myObject.save(flush: true)) {
...

Tags: , ,

One Response to “GORM nullables and unsaved transient instance”

  1. mamram says:

    thanks, params.remove() was the trick…

Leave a Reply