How to establish a hibernate session within a grails script

The following script columns:

// 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) 

failure is excluded:

An error occurred while executing the script Import: org.hibernate.HibernateException: the Hibernate session is not connected to the stream, and the configuration does not allow creating a non-transactional here

when validate () is called on an invalid domain object. I would like to display error messages when the check fails, however it seems to me that for this I need to create a sleep mode session. Does anyone know how to get past this?

+4
source share
2 answers

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

 // Import.groovy def Channel = grailsApp.classLoader.loadClass("content.Channel") def cc = Channel.newInstance(title:"A Channel", slug:"a-channel", position:0).validate() c = Channel.newInstance().validate() println(c.errors) 

I can run it like this:

$> grails run- script scripts / Import.groovy

+3
source

I am doing 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) 
0
source

All Articles