改进groovyq的这篇文章:
http://www.groovyq.net/content/%E8%BF%94%E5%9B%9E%E9%83%A8%E5%88%86doaminclass#comment-179
感谢groovyq对Grails新人的指点.
def excludedProps = [Events.ONLOAD_EVENT,
Events.BEFORE_DELETE_EVENT, Events.AFTER_DELETE_EVENT,
Events.BEFORE_INSERT_EVENT, Events.AFTER_INSERT_EVENT,
Events.BEFORE_UPDATE_EVENT, Events.AFTER_UPDATE_EVENT]
grailsApplication.domainClasses.each{ domainClass ->
/**
* 添加取domain部分属性的功能
* 参数[include:[],except:[],relationship:[]]
*/
domainClass.metaClass.part = {m=[:]->
def map= [id:delegate.id]
if(m.'include'){
m.'include'.each{
map[it] = delegate."$it"
}
}else{
domainClass.persistentProperties.each{
if(!(m.'except' && it.name in m.'except') && !(it.name in excludedProps) && !it.isAssociation()){
map[it.name]= delegate."${it.name}"
}
}
}
m.'relationship'?.each{key,value=null->
def mapKey = value?:key
key.split(/\./).each{propName->
map[mapKey] = (map[mapKey]?:delegate)."$propName"
}
}
return map
}
使用方法:
def instance = SomeDomain.get(0);
//输出所有的非关联属性,以及指定的关联的某几个属性
instance.part( relationship:['bureau.id','bureau.name','bureau.code'] ) as JSON
//{id:1,"code":"AA","descript":null,"floorHeight":null,"floorLoad":null,"floorNo":null,"name":"AAA","bureau.id":0,"bureau.name":"A","bureau.code":"AAA"}
//仅输出指定的非关联属性以及指定的关联属性
instance.part(
include:['code','name'],
relationship:['bureau.name']
)
//{"id":0,code:"aaa","name":"AAA","bureau.name":"A"}
//输出除了id和name外的所有非关联属性以及指定的关联属性.
instance.part(
except:['name'],
relationship:['bureau.name']
)
//{id:0,"code":"AA","descript":null,"floorHeight":null,"floorLoad":null,"floorNo":null,"bureau.name":"A"}
//指定关联属性的命名.
instance.part(
except:['name'],
relationship:['bureau.id':'bureauId','bureau.name':'bureauName']
)
//{id:0,"code":"AA","descript":null,"floorHeight":null,"floorLoad":null,"floorNo":null,"bureauId":"A","bureauName":"A"}
本文介绍了一个 GroovyQ 博客中的 Grails 属性选择技巧,通过定义元类方法 `part` 实现了按需选择 Domain 对象的部分属性及关联属性。该方法支持指定包含、排除及关联属性的选项。
238

被折叠的 条评论
为什么被折叠?



