2010-01-11 70 views
6

我是一个Grails新手(和一个groovy新手),我正在通过一些grails教程。作为一名新用户,grails shell对我来说是一个非常有用的小工具,但我无法弄清楚如何让它看到我的类和对象。这是我想要的: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 

这次我做错了什么?

回答

2

我第二次伯特的建议,使用控制台,而不是壳。关于异常:

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() 
} 
+0

是的,withTransaction完美运作。我想知道为什么我需要补充一点。网上的例子似乎没有提到它。 – 2010-01-11 17:29:51

+0

你不需要补充,但我想它可以解决你的问题。通过在一个事务中运行你的代码,你迫使创建一个hibernate会话(否则它会丢失)。 – 2010-01-11 23:15:57

2

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

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

我更喜欢控制台,它使用起来更容易。运行'grails console',Swing应用程序将启动。它与普通的Groovy控制台有点不同,它有一个隐含的'ctx'变量,它是Spring应用程序的上下文。您可以通过“ctx.getBean('fooService')”来访问服务和其他Spring beans。“

+0

谢谢,很好的建议!附:我还有一个问题,save()会产生一个Hibernate异常。建议? – 2010-01-11 06:23:33

+0

另外,“ctx”似乎也可以在我的shell中使用。也许他们在1.2中添加了它? – 2010-01-11 17:29:10

1

您将必须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> 
+1

啊,我知道保存是一种方法,但我已经足够新,不知道我不能调用没有括号的方法:) 你知道我看到的Hibernate会话异常是怎么回事现在? – 2010-01-11 06:24:25

相关问题