【发布时间】:2011-05-03 14:52:45
【问题描述】:
这个问题涉及在 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 几次之后,我看不出我做错了什么。
关于我做错了什么的任何线索?后备数据库是一个在内存中运行的 HSQLDB,具有默认设置(由 grails create-app 创建)。
编辑:我有点不确定是否应该为公式添加属性字段。如果我确实添加了一个属性字段“双倍正常运行时间”,则断言仍然失败,但这次是因为正常运行时间为 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。我原以为这应该足够了,因为公式中除法返回的数字是浮点数,但似乎适用正常的整数除法规则 - 因为结果始终为零。因此,为了使测试工作,我需要指定所有三个字段都是 Doubles。即使一切正常,查询派生值的对象仍然会给你 null。去图吧。
-
我知道为什么它在属性上返回 null。请参阅我在 Ziad Jayyousi 回答下的最后一条评论。
标签: grails groovy grails-orm formula hibernate-mapping