2012-08-02 91 views
5

我有域“国家”,并在list.gsp我有搜索块与输入字段。 第一个问题是,当我试图在列表中使用paginate时,总是显示所有结果,在这种情况下,我提供了解决方案,并且只发送了10个值(如果您知道另一个解决方案,请告诉我)。我的搜索中查找此:grails分页的搜索结果

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") 
     } 
    } 

现在我有一个问题,当我按下下一个页面,然后我的PARAMS从搜索领域被清洗,结果为空。我试图发送字段值作为参数,但我的事情我做错了什么。

我的搜索页面看起来像:

<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> 

...... ......

+0

Emmmm,你为什么要用搜索引擎,后来用HQL查询? – 2012-08-02 14:36:31

回答

1

如果你有一个非常大的数字在表中的行,这样分页会打破。即使在中等大小的表上,它也会很慢,因为它从数据库的每一行加载。

更好的解决方法是在查询中进行分页。您可以在地图中的查询参数分页作为可选的第三个参数一通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

+0

它是行不通的,我的意思是executeQuery,我有错误Null – 2012-08-02 15:50:47

+0

它没有额外的参数工作吗? – ataylor 2012-08-02 15:55:11

2

最好的解决办法,我发现:

的行动:

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}"/> 

看到一个完整的example

+0

+1提醒我使用'params =“$ {params}”'我想知道为什么我在页面之间丢失参数 – 2015-09-06 18:37:51

0

在params属性中添加params对象。

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