GRAILS 分页 查询

在做grails的查询分页的时候,发现一个问题,那就是输入的查询参数不能作为条件在分页之间传递,而且如果做分页查询的总数也不得而知,针对多条件criteria查询(也适用于HQL查询)做了如下实现,代码如下:
最主要的是蓝色标注的部分,创建新的criteria,用projection的rowCount()方法,统计总条数,查询条件要保持一致,然后制定参数传递给view。
def bookingInstance = new Booking(params)
                def criteria = Booking.createCriteria()
               
                def max = 5
                def offset = 0
                if(params.max) max = params.max.toInteger()
                if(params.offset) offset = params.offset.toInteger()
                def results = criteria {
                    and {
                        if(bookingInstance.employee && session.employee.role=='Admin'){
                            eq('employee',bookingInstance.employee)
                        }
                        if(bookingInstance.meetingRoom){
                            eq('meetingRoom',bookingInstance.meetingRoom)
                        }
                        if(bookingInstance.startDateTime){
                            println bookingInstance.startDateTime
                            ge('endDateTime',bookingInstance.startDateTime)
                        }
                        if(bookingInstance.endDateTime){
                            le('startDateTime',bookingInstance.endDateTime+1)
                        }
                        maxResults(max)
                        firstResult(offset)
                        order('startDateTime', 'asc')
                    }
                }
                def criteria1 = Booking.createCriteria()
                def branchCount = criteria1.get {

                    and {
                        if(bookingInstance.employee && session.employee.role=='Admin'){
                            eq('employee',bookingInstance.employee)
                        }
                        if(bookingInstance.meetingRoom){
                            eq('meetingRoom',bookingInstance.meetingRoom)
                        }
                        if(bookingInstance.startDateTime){
                            println bookingInstance.startDateTime
                            ge('endDateTime',bookingInstance.startDateTime)
                        }
                        if(bookingInstance.endDateTime){
                            le('startDateTime',bookingInstance.endDateTime+1)
                        }
                    }
                    projections {
                        rowCount()
                    }
                }
                params.branchCount = branchCount
                 params.page = 1
                println "${branchCount}nnnn"    
                render(view:'searchresults',model:[ bookingInstanceList: results,params:params ])


view的代码如下:
<g:paginate controller="booking"
                        action="search" total="${params.branchCount}"
                        max="5" maxsteps="4" params="${params}" />
主要是指定max,params,total参数,这样就可以在分页查询中传递参数了。

你可能感兴趣的:(grails)