Grails的Controller中如何获取Domain模型

问题的提出: 
domain模型的定义如下,如何在Controller中取得domain模型的元数据 

Java代码   收藏代码
  1. package application  
  2.   
  3. class Bird {  
  4.   
  5.     static domain=[chinese:"鸟"]  
  6.   
  7.     String name  
  8.     String gender  
  9.   
  10.     static constraints = {  
  11.         name(attributes:[chinese:"名称"])  
  12.         gender(attributes:[chinese:"性别"],inList:["公","母"])  
  13.     }  
  14. }  


问题的解决: 

Java代码   收藏代码
  1. def birdClass=grailsApplication.getArtefact("Domain","application.Bird")  
  2. def cps=birdClass.getConstrainedProperties()  
  3. def classChinese=Bird.domain.chinese  
  4. def properties=[:]  
  5.   
  6.     def index = {  
  7.     redirect(action: "list", params: params)  
  8. }  
  9.   
  10. def list = {  
  11.   
  12.     params.max = Math.min(params.max ? params.int('max') : 10100)  
  13.     println cps  
  14.     println "propiety:"  
  15.     birdClass.getProperties().each{  
  16.         def namePropertiy=it.getName()  
  17.   
  18.         if(namePropertiy == 'id')  
  19.         {  
  20.             properties[namePropertiy]='编号'  
  21.         }else if(namePropertiy == 'dateCreated')  
  22.         {  
  23.             properties[namePropertiy]='创建时间'  
  24.         }else if(namePropertiy == 'lastUpdated')  
  25.         {  
  26.             properties[namePropertiy]='更新时间'  
  27.         }else if(it.isPersistent()==true && cps[namePropertiy]!=null && namePropertiy!='version'){  
  28.             properties[namePropertiy]=cps[namePropertiy].attributes.chinese?:namePropertiy  
  29.         }else{  
  30.             println "SHIT:"+namePropertiy  
  31.         }  
  32.     }  
  33.     println classChinese  
  34.     println properties  
  35.   
  36.     [birdInstanceList: Bird.list(params), birdInstanceTotal: Bird.count(),classChinese:classChinese,properties:properties]  
  37. }  



Html代码   收藏代码
  1. <g:set var="entityName" value="${classChinese}" />  
  2. <div class="list">  
  3.   <table>  
  4.     <thead>  
  5.       <tr>               
  6.         <g:sortableColumn property="id" title="${properties.id}" />  
  7.                          
  8.         <g:sortableColumn property="name" title="${properties.name}" />  
  9.                          
  10.         <g:sortableColumn property="gender" title="${properties.gender}" />  
  11.                          
  12.       </tr>  



最终效果: 
 

心得体会: 
做这件事情的最初想法是希望将ConventionOverConfiguration的思想贯彻的更彻底些,将中文化的工作直接“注入”到Grails Scaffolding的过程中,但由于Scaffolding过程中加载的Domain类并非最终类,因此无法正常读取相关元数据,因此最终采用Controller读取数据,通过预先约定好的数据传递给Views的方法,终于把这个“鸟”问题的解决方案整了一个思路出来。 

后续还需要完善的地方: 

  • 类关系处理(1:M, M:1, M:N)
  • 通过Controller继承的方式将取Domain类元数据过程“隐藏”

猜你喜欢

转载自alanland.iteye.com/blog/2008430