Grails + EJB Domain Models

gudesheng發表於2008-01-03

Ruby on Rail儘管不斷吸引軟體工程領域的注意,但企業級的開發室仍然對其很不信任.為什麼?“基於指令碼語言的框架難道也能符合企業級應用麼?!” 對於RoR,最主要的論據就是他們缺乏企業級服務(例如分散式事務,訊息等)。對很多業務來說,沒有這些服務的平臺是根本不予考慮的。

Grail就是一個快速的企業級快速應用開發工具。它基於Groovy語言,可以無縫的整合Java的服務,同時也提供了指令碼語言的巨大便利。

為了顯示它的企業整合能力,Grails可以快速方便的構建一個web應用程式,後端使用EJB3實體beans。但是,不僅僅如此,Grails讓你可以對實體bean實現動態控制,而不需要你修改EJB的原始碼。Grails Object Relational Mapping (GORM)是基於Hibernate 3的(最終也會支援Java Persistence API),並且使用Groovy's Meta Object Protocol (MOP)來新增各種手工動態方法給實際上靜態的實體bean。這些方法不僅可以給Grails和Groovy呼叫;Java程式碼也可以呼叫。這樣我們就同時擁有了JEE/EJB3的企業級能力和RAD web應用開發的便利。

Rails的程式碼生成就不用說了,RoR做到的,它都能做到,下面看看他的擴充程式碼

import com.jasonrudolph.ejb3example.entity.EmployeeBean

新增一個web事件
和RoR相比,Grail對物件關聯的處理十分靈活
def showComputersByEmployee = {
    render(view:'list', model:[ computerBeanList:
 ComputerBean.findAllByEmployeeBean(EmployeeBean.get(params.id)) ])
}

儲存web提交
def update = {
    def computerBean = ComputerBean.get( params.id )
    if(computerBean) {
           if (computerBean.employeeBean) {
                  computerBean.employeeBean.computers.remove(computerBean)
           }

           computerBean.properties = params

           def employeeBean = EmployeeBean.get(params.employeeId)
           employeeBean.computers.add(computerBean)
           computerBean.employeeBean = employeeBean

           if(computerBean.save()) {
                  redirect(action:show,id:computerBean.id)
           }
           else {
                  render(view:'edit',model:[computerBean:computerBean])
           }
    }
    else {
           flash.message = "ComputerBean not found with id ${params.id}"
           redirect(action:edit,id:params.id)
    }
}


驗證規則
這是Grails的另一個特色
constraints = {
      networkId(length:6..8,blank:false,unique:true)
      firstName(maxLength:20,blank:false)
      lastName(maxLength:20,blank:false)
      startDate(nullable:false)
}


查詢事件
def showSearchResults = {
    render(view:'list', model:[ employeeBeanList:
        EmployeeBean.findAllByLastNameLike("%" + params.lastName + "%") ])
}

高階查詢
def showSearchResults = {
    def criteria = EmployeeBean.createCriteria()

    def results = criteria {
        or {
            ilike("networkId", "%" + params.networkId + "%")
            and {
                eq("firstName", params.firstName)
                eq("lastName", params.lastName)
            }
        }
    }

    render(view:'list', model:[ employeeBeanList: results.adaptee ])
}

 


 



Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=1116386


相關文章