如何在 grails 脚本中建立 Hibernate 会话
题
以下 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 Session 绑定到线程,并且配置不允许在此处创建非事务性会话
当对无效域对象调用 validate() 时。我想在验证失败时输出错误消息,但似乎我需要建立一个休眠会话才能执行此操作。有人知道有办法克服这个吗?
解决方案
成立 RunScript.groovy 它为您设置休眠会话,然后运行您指定为参数的脚本。我必须将我的源代码从甘特脚本(上面)更改为简单的:
// 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)
我可以像这样运行它:
$> grails 运行脚本脚本/Import.groovy
其他提示
我在做这样的事情,它为我的作品...
// 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)
不隶属于 StackOverflow