代码之家  ›  专栏  ›  技术社区  ›  dstnbrkr

如何在Grails脚本中建立休眠会话

  •  4
  • dstnbrkr  · 技术社区  · 15 年前

    以下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:没有绑定到线程的休眠会话,并且配置不允许在此处创建非事务性会话

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

    2 回复  |  直到 13 年前
        1
  •  3
  •   dstnbrkr    15 年前

    发现 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

        2
  •  0
  •   cowabunga1984    13 年前

    我在做这样的事,这对我很有用…

    // 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)
    
    推荐文章