grails的criteria实现复合查询并实现结果分页

def search = {
        if(!params.max) params.max = 10
        if(!params.offset) params.offset = 0
        def searchClosure =  {
            if(params.categoryName) {
                category{
                    eq('categoryName', params.categoryName);
                }
            }
            if(params.title) {
                like('title',"%${params.title}")
            }
            if(params.priceLow) {
                ge('price', new BigDecimal(params.priceLow))
            }
            if(params.priceHigh) {
                le('price', new BigDecimal(params.priceHigh))
            }
            if(params.description) {
                like('description', "%${params.description}")
            }
        }
        def c = Goods.createCriteria();
        params.sort = "price"
        params.order = "asc"
        def goodList = c.list (params, searchClosure)
        def goodsCount = goodList.totalCount

        render (view: 'list', model: [goodsInstanceList: goodList, goodsInstanceTotal: goodsCount])
    }

使用闭包封装查询条件如上面的searchClosure闭包,这样就可以重复使用查询条件了,
在list的时候会返回一个PagedResultList类型,里面就有totalCount属性,表示符合查询条件的记录数,这样就不用count了。在list的时候可以传入分页参数组成的map如上面的params参数,这样就不用在查询闭包里设置分页参数了

你可能感兴趣的:(分页,grails)