2011-05-03 44 views
0

这个问题涉及在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_

+0

我似乎已经解决了它。有些。 为了使它工作,我需要添加一个名为uptime的字段,它是一个Double。我会认为这应该是足够的,因为公式中分部返回的数字是一个浮点数,但似乎适用正常的整数除法规则 - 因为结果总是为零。 所以为了使测试工作,我需要指定所有三个字段都是双精度。 即使一切正常,查询派生值的对象仍然会给你null。去搞清楚。 – oligofren 2011-05-03 15:56:46

+0

我想出了它为什么在属性上返回null。在Ziad Jayyousi的回答下查看我的最新评论。 – oligofren 2011-05-04 09:24:54

回答

2

在一段时间内没有新的答案,所以我张贴的和式:

  • 必须有一个FIEL d为公式才能运作。
  • 派生属性始终是可搜索的,因为这涉及到数据库搜索,但如果保存的版本仍在缓存中,则对象的属性将始终为空。总之:清除会话缓存之前搜索或刷新缓存的对象(obj.refresh())

最后一点,手动刷新,似乎很不起眼,但我还没有找到解决办法。

1

第一:正常运行时间不是原始的,也不是类型。也不知道你为什么使用映射。或者你可以在你的类中创建一个短暂的财产“正常运行时间”,然后给它一个getter方法:

我会用,而不是整型双:

class Derive { 
    Integer up 
    Integer down 
    static transients = ['uptime'] 

    Integer getUptime(){ 
     Integer uptime = up/(down+up)  
     return uptime 
    } 
} 

然后访问它在你的代码:

def derive = new Derive() 
def uptime = derive.uptime 
+0

“正常运行时间不是原始的,也不是类型的”是什么意思?你的意思是它是无类型的?如果是这样,我应该添加一个字段的名称和类型的类? – oligofren 2011-05-03 15:29:48

+0

至于为什么...通常只是做简单的事情知道它的作品对我来说足够宝贵。 – oligofren 2011-05-03 15:34:33

+0

class Derive { Double up Double down Double正常运行时间 ... 任何想法为什么这不起作用吗?这里没有整数除法,但在测试中我仍然只是得到0/null。 – oligofren 2011-05-03 15:35:51