Grails小技巧

来源:互联网 发布:单片机pwm红外发射 编辑:程序博客网 时间:2024/06/03 15:59
Grails小技巧 
一、Controlller中params 
Controlller中params是grails框架中的GrailsParameterMap类,继承自TypeConvertingMap,而不是一个简单的Map, 
除了支持普通的Map方法以外,还有其他几个方法非常有用 
Java代码 
Integer int(String name);  
Long long(String name);  
Double double(String name);  
Short(String name);  
List list(String name);  

若需要得到数值类型的参数就非常方便了 
Java代码 
int max= params.int("max")?:10;  


二、分页 
其实使用Grails做分页功能是最easy的事情,因为Domain类的Criteria的list方法返回的结果就是带有分页所用信息的PagedResultList类 
Domain的动态方法会检查是否调用的是list方法,若是则会使用Hibernate Criteria.setProjection(Projections.rowCount())方法,根据条件查询总数。想深入了解可以看看HibernateCriteriaBuilder.java源码。 
Java代码 
public class HibernatePluginSupport {  
    private static addQueryMethods(GrailsDomainClass dc, GrailsApplication application, ApplicationContext ctx) {  
        ...;  
        metaClass.static.createCriteria = {-> new HibernateCriteriaBuilder(domainClassType, sessionFactory)}  
        ...;  
  
    }  
}  
//groovy 动态机制  
public class HibernateCriteriaBuilder {  
    public Object invokeMethod(String name, Object obj){  
        createCriteriaInstance();  
  
        // 检查分页参数,一个参数是Map,包含分页参数  
        if(name.equals(LIST_CALL) && args.length == 2) {  
            paginationEnabledList = true;  
            orderEntries = new ArrayList();  
            invokeClosureNode(args[1]);  
        } else {  
            invokeClosureNode(args[0]);  
        }  
        ...  
        if(paginationEnabledList) {  
            this.criteria.setFirstResult(0);  
            this.criteria.setMaxResults(Integer.MAX_VALUE);  
            this.criteria.setProjection(Projections.rowCount());  
            int totalCount = ((Integer)this.criteria.uniqueResult()).intValue();  
  
            // Drop the projection, add settings for the pagination parameters,  
            // and then execute the query.  
            this.criteria.setProjection(null);  
            for(Iterator it = orderEntries.iterator();it.hasNext();){  
                this.criteria.addOrder(it.next());  
            }  
            this.criteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);  
            GrailsHibernateUtil.populateArgumentsForCriteria(targetClass, this.criteria, (Map)args[0]);  
            PagedResultList pagedRes = new PagedResultList(this.criteria.list());  
  
            // Updated the paged results with the total number of records  
            // calculated previously.  
            pagedRes.setTotalCount(totalCount);  
            result = pagedRes;  
        }  
  
    }  
}  

PagedResultList类除了实现List接口外,添加了totalCount属性即记录总数,然后view层max和offset参数来控制分页就可以了,非常的方便 
Java代码 
//params已有order、sort、max、offset的分页排序信息  
params.max = Math.min(params.int('max') ?: 15, 100)  
def criteria = CellPhoneModel.createCriteria();  
def pageList = criteria.list(params, {  
  if(params['factory.id'])  
    factory {  
      eq("id",params.long('factory.id'))  
    }  
  if(params.keyword)  
    like("abbreviateName","%${params.keyword}%")  
 });