Search code examples
hibernategrailsgrails-ormbootstrapping

Creating a domain instance with a hibernate event from BootStrap.groovy


I am attempting to create a User domain object in my BootStrap.groovy file but receive the following error:

[ERROR]:AssertionFailure  an assertion failure occured (this may indicate a bug in Hibernate, but is more likely due to unsafe use of the session)

The domain object is shown below: the problem occurs when calling a service from within the afterInsert method. The service is non-null and invoking any method on it, including toString() or inspect(), seems to cause the error.

BootStrap.groovy

def newUser = new User(...)
newUser.save(flush:true, failOnError: true)    

User.groovy

class User extends Auth {
    transient def userService

    ...

    def afterInsert() {
        log.debug "SERVICE: ${userService == null ? 'NULL': 'NOT NULL'}" // Gives: SERVICE: NOT NULL

        // Either of the following lines cause the error when uncommented
        //log.debug "SERVICE: ${userService.toString()}"
        //userService?.makeUser(this)
    }

}

Should this be possible using BootStrap or do I have something fundamentally wrong?

Alternatively, is it possible to ignore this code when called from BootStrap? E.g. Something similar to:

def afterInsert() {
    if (notBootStrap()) {
        ...
    }
}

Any input will be greatly appreciated!


Solution

  • Service needs a transaction.

    def afterInsert() {
            User.withTransaction{
               userService.makeUser(this)
            }
        }