DRY:巧用Domain Class属性

常听到“程序员的工作就是拷贝、粘贴”,诸如此类的抱怨。那么在使用Grails的时候,能不能避免出现这种情况呢?做到“Don't Repeat Yourself (DRY)”。Don Denoncourt在博文中分享了他的经验:多个Doamin Class使用一个list.gsp显示,即动态使用Domain class中定义的属性。

在Domain Class中可以使用CustDomainName.properties.declaredFields获得所有的字段,但其中有些是不需要显示出来的,比如version、constraints。我们需要将list.gsp中要显示的字段筛选出来,使用modifiers进行区分:

  • modifiers = 2:表示其为用户自定义字段;
  • modifiers = 10:表示其为缺省的静态字段,如constraints、namedQueries;
  • modifiers = 0:表示其为自动创建的字段,如id、version。

示例代码如下:

 

static List getColumnProperties() {
    def columnProperties = []		
    CustDomainName.properties.declaredFields.each {prop ->
        if (prop.modifiers == 2)
            columnProperties <<prop
    }
    return columnProperties
}

这样columnProperties就是我们需要字段列表,在Controller中通过“[properties:CustDomainName.columnProperties]”,就可以将其传递给list.gsp。在list.gsp中,也需要动态处理这些个属性,方法介绍如下:

  • 获取属性类型:
  • <g:each in="${properties}" var="property">
    ......
      ${property.type.name}
    ......
    </g:each>
    
  • 获取属性名称:
  • <g:each in="${properties}" var="property">
    ......
      ${property.name}
    ......
    </g:each>
    
  • 获取属性值:
  • <g:each in="${properties}" var="property">
    ......
       ${domainObj[property.name]}
    ......
    </g:each>
    

采用类似的方法,也可以对namedQueries(命名查询)进行改造,使其能够满足我们的需求,这里就不赘述。

更多详细内容以及完整的示例代码请参见Don Denoncourt的原文

关于命名查询,请参见本站文章“Grails中的命名查询”。

By huwh - Posted on 27 六月 2010

請問一下如果我有一個 Stutdent class{   

請問一下如果我有一個

Stutdent class{

   String name

   int age

   .......還有很多property

}

然後params 裡面為 name:danny , age:26 .........

要如何比較Stutdent.get(1)  和  params 中哪個property是不同的

如  Stutdent.name = amy 和  param.name=danny ---> 此時我就發現name不同

 

如果是非常多property我不可能一個一個又比較 有什麼簡易方法可以簡單比較property不同的呢?

 

试试getDirtyPropertyNames。

在Grails 1.3中,Domain Class已经getDirtyPropertyNames方法了,该方法的作用就是检测Domain Class里面那些属性被修改了。