这个问题涉及在Grails的静态映射块中使用公式字段。找不到Grails公式字段
我试图实现一个使用公式映射(派生属性)的非常简单的域类,但我一直得到一个“No property found for name [uptime]
”,其中运行时间是Grails域类中的派生属性。该代码是如下(简化):
class Derive {
Integer up
Integer down
static mapping = {
uptime formula : "UP/(DOWN+UP)"
}
}
class DeriveTests extends GroovyTestCase {
void testDerivedProp() {
new Derive(up:10, down:5).save()
new Derive(up:5, down:5).save()
assertEquals Derive.all.size(),2
assertEquals 2,Derive.findAllByUptimeGreaterThan(0.1).size() //fails here
assertEquals 2,Derive.findAllByUptimeGreaterThan(10/(10+5)).size()
}
}
运行测试给我一个错误在第二的assertEquals:org.codehaus.groovy.grails.exceptions.InvalidPropertyException: No property found for name [uptime] for class [class Derive]
。我在这里看不到我做错了什么,在几次参考Grails In Action和reference docs之后。
任何线索,我做错了什么?后台数据库是一个内存中运行的默认设置(由grails create-app创建)的HSQLDB。
编辑:我有点不确定是否应该为公式添加属性字段。如果我添加属性字段'Double uptime',则断言仍然失败,但这次是因为正常运行时间为0.在调试器中查看对象显示正常运行时间为空。不过,sql输出显示了一些看起来正确的东西:hibernate.SQL select this_.id as id6_0_, this_.version as version6_0_, this_.down as down6_0_, this_.up as up6_0_, this_.UP*100/(this_.DOWN+this_.UP) as formula0_0_ from derive this_
我似乎已经解决了它。有些。 为了使它工作,我需要添加一个名为uptime的字段,它是一个Double。我会认为这应该是足够的,因为公式中分部返回的数字是一个浮点数,但似乎适用正常的整数除法规则 - 因为结果总是为零。 所以为了使测试工作,我需要指定所有三个字段都是双精度。 即使一切正常,查询派生值的对象仍然会给你null。去搞清楚。 – oligofren 2011-05-03 15:56:46
我想出了它为什么在属性上返回null。在Ziad Jayyousi的回答下查看我的最新评论。 – oligofren 2011-05-04 09:24:54