1. findAll
通过写HQL语句查询符合条件的记录如:
Book.findAll("fromBook as b where b.author=:author",[author:'Dan Brown'], [max:10, offset:5])
使用了参数作为查询条件,同时提供了分页的参数map:[max:10, offset:5]
2.findAllBy
比较常用的动态查询方法之一,可实现分页查询如:
Book.findAllByTitle("TheShining",[max:10, sort:"title",order:"desc",offset:100] )
指定查询条件,按Title=TheShining查询,同时指定分页参数map:[max:10,sort:"title",order:"desc",offset:100]
3.list
list也是比较常用的动态查询方法之一,列出所有实例如:
def results = Book.list(max:10, offset:100,sort:"title",order:"desc")
可以指定分页参数
4.criteria.list
比较常用的查询方法之一,可以在list中指定查询闭包,和分页参数map如:
def c = Goods.createCriteria()
params.sort= "price"
params.order= "asc"
defgoodList = c.list (params, searchClosure)
其中,params为分页参数,searchClosure为查询条件闭包
def search = {
if(!params.max)params.max = 10
if(!params.offset)params.offset = 0
defsearchClosure = {
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}")
}
}
defc = Goods.createCriteria();
params.sort= "price"
params.order= "asc"
defgoodList = c.list (params, searchClosure)
// defgoodsCount = c.count (searchClosure)
defgoodsCount = goodList.totalCount
printlngoodsCount
render(view: 'list', model: [goodsInstanceList: goodList,goodsInstanceTotal: goodsCount])
}
使用闭包封装查询条件如上面的searchClosure闭包,这样就可以重复使用查询条件了,
在list的时候会返回一个PagedResultList类型,里面就有totalCount属性,表示符合查询条件的记录数,这样就不用count了。在list的时候可以传入分页参数组成的map如上面的params参数,这样就不用在查询闭包里设置分页参数了