4

以下 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: No Hibernate Session bound to thread,并且配置不允许在此处创建非事务性会话

在无效域对象上调用 validate() 时。我想在验证失败时输出错误消息,但似乎我需要建立一个休眠会话才能这样做。任何人都知道克服这个问题的方法吗?

4

2 回答 2

3

找到为您设置休眠会话的RunScript.groovy,然后运行您指定为参数的脚本。我不得不将源代码从 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)

我可以像这样运行它:

$> grails 运行脚本脚本/Import.groovy

于 2009-03-24T18:12:16.107 回答
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)
于 2011-09-02T10:59:53.960 回答