GrailsShell看不到域对象

GrailsShell看不到域对象,grails,groovy,groovyshell,Grails,Groovy,Groovyshell,我是一个grails新手(也是一个groovy新手),我正在学习一些grails教程。作为一个新用户,GrailsShell对我来说是一个非常有用的小工具,但我不知道如何让它看到我的类和对象。以下是我正在尝试的: % grails create-app test % cd test % grails create-domain-class com.test.TestObj % grails shell groovy:000> new TestObj() ERROR org.codehaus

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

% 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
我的印象是GrailsShell可以看到所有的控制器、服务和域对象。这是怎么回事?我需要在这里做些别的事情吗

我尝试了另一件事:

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

这次我做错了什么?

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

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


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

您必须
导入com.test.TestObj
或通过
新建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> 

我赞同伯特的建议,使用控制台而不是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()
}

谢谢,好建议!另外,我还有一个问题,save()生成一个Hibernate异常。建议?另外,“ctx”似乎也可以在我的shell中使用。也许他们在1.2中添加了它?啊,我知道save是一个方法,但我对groovy来说太新了,以至于我不知道我不能调用没有括号的方法:)你知道我现在看到的Hibernate会话异常是怎么回事吗?是的,withTransaction工作得很好。我想知道为什么我需要补充这一点。网上的例子似乎没有提到这一点。你不需要添加这一点,但我认为这可能会解决你的问题。通过在事务中运行代码,您可以强制创建hibernate会话(否则将丢失该会话)。