【问题标题】:Grails shell not seeing domain objectsGrails shell 看不到域对象
【发布时间】:2011-01-03 15:31:28
【问题描述】:

我是一个 grails 新手(也是一个 groovy 新手),我正在学习一些 grails 教程。作为一个新用户,grails shell 对我来说是一个非常有用的小工具,但我不知道如何让它看到我的类和对象。这是我正在尝试的:

% grails create-app test
% cd test
% grails create-domain-class com.test.TestObj
% grails shell
groovy:000> new TestObj()
ERROR org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed, groovysh_evaluate: 2: unable to resolve class TestObj

我的印象是 grails shell 可以看到所有的控制器、服务和域对象。这是怎么回事?我需要在这里做点别的吗?

我尝试了另一件事:

groovy:000> foo = new com.test.TestObj();
===> com.test.TestObj : null
groovy:000> foo.save 
ERROR groovy.lang.MissingPropertyException: No such property: save for class: com.test.TestObj

我做错了什么?

编辑:好的,我看到了有关使用全名以及使用.save() 而不是.save 的答案。但是这个呢?

groovy:000> new com.test.TestObj().save()
ERROR org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here

这次我做错了什么?

【问题讨论】:

    标签: grails groovy groovyshell


    【解决方案1】:

    我赞同 Burt 的建议,即使用控制台而不是 shell。关于异常:

    groovy:000> new com.test.TestObj().save()
    ERROR org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here
    

    您能否尝试使用事务显式运行此代码:

    import com.test.TestObj
    
    TestObj.withTransaction{ status ->
        TestObj().save()
    }
    

    【讨论】:

    • 是的,withTransaction 完美运行。我想知道为什么我需要添加它。网上的例子好像没有提到。
    • 您不需要添加它,但我认为它可能会解决您的问题。通过在事务中运行代码,您会强制创建休眠会话(否则会丢失)。
    【解决方案2】:

    您必须import com.test.TestObj 或通过new com.test.TestObj() 引用它,如您所示。

    请注意,'save' 不是属性,而是 Grails 在运行时装饰域类的动态方法。

    groovy:000> foo = new com.test.TestObj();
    ===> com.test.TestObj : null
    groovy:000> foo.save()
    ===> com.test.TestObj : 2
    groovy:000> 
    

    【讨论】:

    • 啊,我知道 save 是一种方法,但我太新了,不知道我不能在没有括号的情况下调用方法 :) 你知道 Hibernate 会话是怎么回事我现在看到的异常?
    【解决方案3】:

    您需要该包,因为可能(但不是一个好主意)在不同的包中拥有两个同名的域类。

    对于第二个会话,它应该是 foo.save(),而不是 foo.save。

    我更喜欢控制台,它更易于使用。运行“grails 控制台”,Swing 应用程序将启动。它与常规的 Groovy 控制台有点不同,因为它有一个可用的隐式“ctx”变量,即 Spring 应用程序上下文。您可以使用它通过“ctx.getBean('fooService')”访问服务和其他 Spring bean

    【讨论】:

    • 谢谢,好建议!附言我还有一个问题,save() 会产生 Hibernate 异常。有什么建议吗?
    • 另外,“ctx”似乎也可以在我的 shell 中使用。也许他们在 1.2 中添加了它?
    猜你喜欢
    • 2010-12-29
    • 1970-01-01
    • 2014-07-09
    • 2015-04-01
    • 2013-10-09
    • 1970-01-01
    • 1970-01-01
    • 2011-09-18
    • 2015-01-06
    相关资源
    最近更新 更多