搜索结果的grails分页



我有域"country",在列表.gsp上有带输入字段的搜索块。第一个问题是,当我试图在我的列表中使用分页时,总是显示所有结果,在这种情况下,我找到了解决方案,我只发送了10个值来显示(如果你知道其他解决方案,请告诉我)。我的搜索如下:

    def search = {
       if(query){
           def srchResults = searchableService.search(query, params)
           def result =  Country.executeQuery("select  new map(a.name as name, a.datacenter as datacenter) from Country a where a.name like '%"+ params.q + "%'")
           if (params.offset)
           {
               x = params.offset.toInteger()
               y = Math.min(params.offset.toInteger()+9, result.size()-1)
           } else
            {
            x = 0
            size = result.size() - 1
            y = Math.min(size, 9)
             }     
           def q=params.q
          [countryInstanceList: result.getAt(x .. y), countryInstanceTotal:result.size(), q:params.q]
       }else{
           redirect(action: "list")
       }
   }

现在我有另一个问题,当我按下下一页时,我的参数从搜索字段中清除,结果为空。我试图将字段值作为参数发送,但我认为我做错了。

我的搜索页面看起来像:

<g:form action="search">
            <div class="search" >
                Search Country
                <g:hiddenField name="q" value="${params.q}" />
                <input type="text" name="q" value="${params.q}" />
                <input type="submit" value="Search"/>
            </div>
        </g:form>

。。。。。。

我找到的最佳解决方案:

行动:

def list() {
... //use params to filter you query and drop results to resultList of type PagedResultList
return [resultList: resultList, resultTotal: resultList.getTotalCount(), filterParams: params]
}

视图:

<g:paginate total="${resultTotal}" action="list" params="${filterParams}"/>

请参阅完整的示例。

如果表中有大量的行,那么像这样的分页就会中断。即使在中等大小的表上,它也会非常慢,因为它会从数据库的每一行加载。

更好的解决方案是在查询中进行分页。您可以将用于分页的查询参数映射作为可选的第三个参数传递给executeQuery:

def maxResults = 10
def result = Country.executeQuery(
    "select  new map(a.name as name, a.datacenter as datacenter) from Country a where a.name like ?", 
    [params.q], 
    [max: maxResults, offset: params.offset])

此外,您的表单有两个名称为q的字段。不要使用与文本输入同名的隐藏字段。可以使用value属性指定文本输入的默认值。

最后,您必须将偏移量作为参数传递。Grails有一个标签可以为您处理所有这些:g:paginate

在params属性中添加params对象。

<g:paginate total="${resultTotal}" action="list" params="${params}"/>

最新更新