findAll() HQL not returning paginated list in grai

2019-07-06 00:10发布

问题:

I am working on a grails application, in this I have to apply filter box on list.gsp. When I am filtering using following query(in my service) I am getting paginated list :

    def clientCriteria = TripOrder.createCriteria()
        def searchResults = clientCriteria.list(max: params.max, offset: params.offset, sort: params.sort, order: params.order){
            ilike("origin", "${searchFor}%")
        }
        println searchResults.getTotalCount()
        [searchResults: searchResults, searchResultSize: searchResults.getTotalCount()]

But my problem is that when I am using findAll, I am not able to get paginated list, query as follows :

def searchResults =  TripOrder.findAll("from TripOrder as t where t.status.status=:status", [status: searchFor], [max: maximum, sort: params.sort, order: params.order])

            println searchResults.size()

            [searchResults: searchResults, searchResultSize: searchResults.size()]

Note : Because of some reasons I have to use findAll() HQL instead criteria queries.

Above result provide only number of list equal to max instead of provide paginated list.

Please provide me solution for getting paginated list using findAll().

Thanks.

回答1:

Based on your comment, you can do like this where you get a PagedResultList

def results = TripOrder.createCriteria.list(params) {
    customer {
       ilike 'firstName', "%$searchFor%" 
    }
}

assert results.size() != results.totalCount

It basically fires another query for the totalCount, if you want to stick to findAll or something like findAll instead of criteria then you can imbibe a better alternative by using a DetachedCriteria/where query which lazily executes the query on demand. Again, you won't be able to get the total count in first query. You have to fire another for the same.

def query = TripOrder.where {
    customer.firstName =~ searchFor
}

//Query executed only when list() is called
def results = query.list( params )

//Only executed when count() is called
def totalCount = query.count()


回答2:

findAll isn't designed to return a paginated list. It returns an array. This is clearly stated in the documentation.