Question

The following grails script:

// Import.groovy

includeTargets << grailsScript("Bootstrap")

target(main: "Import some data...") {
    depends(bootstrap)

    def Channel = grailsApp.classLoader.loadClass("content.Channel")

    def c 

    // works: saving a valid Channel succeeds
    c = Channel.newInstance(title:"A Channel", slug:"a-channel", position:0).validate()

    // doesn't work: saving an invalid Channel fails with exception
    c = Channel.newInstance().validate()

    // this line is never reached due to exception
    println(c.errors)

}

setDefaultTarget(main) 

fails with the exception:

Error executing script Import: org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here

when validate() is called on an invalid domain object. I'd like to output the error messages when validation fails, however it seems I'll need to establish a hibernate session in order to do so. Anyone know a way to get past this?

Was it helpful?

Solution

Found RunScript.groovy which sets up the hibernate session for you, then runs the scripts you specify as arguments. I had to change my source from a Gant script (above) to simply:

// Import.groovy

def Channel = grailsApp.classLoader.loadClass("content.Channel")

def c 
c = Channel.newInstance(title:"A Channel", slug:"a-channel", position:0).validate()
c = Channel.newInstance().validate()
println(c.errors)

I'm able to run it like so:

$> grails run-script scripts/Import.groovy

OTHER TIPS

I am doint something like this and it works for me...

// Import.groovy

includeTargets << grailsScript("Bootstrap")

target(main: "Import some data...") {
    depends(bootstrap)

    // added this ------------------------------------------------------
    def sessionFactory = appCtx.getBean("sessionFactory")
    def session = SessionFactoryUtils.getSession(sessionFactory, true)
    TransactionSynchronizationManager.bindResource(
        sessionFactory, new SessionHolder(session))
    // added this ------------------------------------------------------

    def Channel = grailsApp.classLoader.loadClass("content.Channel")

    def c 

    // works: saving a valid Channel succeeds
    c = Channel.newInstance(title:"A Channel", slug:"a-channel", position:0).validate()

    // doesn't work: saving an invalid Channel fails with exception
    c = Channel.newInstance().validate()

    // this line is never reached due to exception
    println(c.errors)

}

setDefaultTarget(main)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top