以下grails脚本:
// 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)
因例外而失败:
执行脚本导入错误:org.hibernate.HibernateException:没有Hibernate会话绑定到线程,并且配置不允许在这里创建非事务性的
在无效域对象上调用validate()时。我想在验证失败时输出错误消息,但似乎我需要建立一个hibernate会话才能这样做。有人知道如何通过这个吗?
答案 0 :(得分:3)
找到RunScript.groovy为您设置hibernate会话,然后运行您指定为参数的脚本。我不得不将我的源代码从Gant脚本(上图)更改为:
// 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)
我可以像这样运行它:
$&GT; grails run-script scripts / Import.groovy
答案 1 :(得分:0)
我正在做这样的事情,它对我有用......
// 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)