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')
}
}
<span style="color:blue">def criteria1 = Booking.createCriteria()
def branchCount = criteria1.get {</span>
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)
}
}
<span style="color:blue">projections {
rowCount()
}</span> }
<span style="color:blue">params.branchCount = branchCount
params.page = 1
println "${branchCount}nnnn"
render(view:'searchresults',model:)</span>
view的代码如下: <g:paginate controller="booking" action="search" total="${params.branchCount}" max="5" maxsteps="4" params="${params}" /> 主要是指定max,params,total参数,这样就可以在分页查询中传递参数了。
理论上是可以返回个PagedResultList类型对象,里面可以包含List和count. 但我现在只要返回PagedResultList, 程序就会报错.!
上面一段是演示不分页的,下面一段是演示分页的。。
不过这个方案不是最好的了,看一下SSailYang的回复:
不觉得有一大段的代码写了两遍吗
thanks!
我搞明白了,SSailYang您太有才了,这个我找了很多api和参考,竟然没有找到。
如果有相应的参考文档,还请共享。
criteria的list方法,如果指定max:x,offset:y参数,返回的是PageResultList类型,如果不指定,是返回的ArrayList类型。
这太有才了。
我可能方法不对,但是按照你提到的做了,好像没有totalCount这么一个属性。
不用这么麻烦。如果你向 list 方法中传递分页信息
list 方法将返回 PagedResultList 类型的对象。你可以通过 PagedResultList 中的 totalCount 属性得到记录的总数。