ExtGrid数据库分页实现

转载自http://ext.group.iteye.com/group/blog/201891

 

看了robbin 关于hibernate 分页的老帖(http://www.iteye.com/topic/261),把ext grid 的数据库分页整了下,完全满足需要,呵呵,贴出代码与大家共同学习下:
DAO代码:
Java代码 复制代码
  1.   /**  
  2.        * 获取符合查询条件的记录总数  
  3.        * @param detachedCriteria  hibernate Criteria 查询对象,由service组装  
  4.        * @return  
  5.        */  
  6.   public Long getRecordCount(final DetachedCriteria detachedCriteria) {   
  7.         return (Long) getHibernateTemplate().execute(new HibernateCallback() {   
  8.             public Object doInHibernate(Session session)   
  9.                     throws HibernateException {   
  10.                 Criteria criteria = detachedCriteria   
  11.                         .getExecutableCriteria(session);   
  12.                 long count = Long.parseLong((criteria.setProjection(Projections   
  13.                         .rowCount()).uniqueResult()).toString());   
  14.                 criteria.setProjection(null);   
  15.                 return Long.valueOf("" + count);   
  16.             }   
  17.         }, true);   
  18.     }   
  19. /**  
  20.        * 获取符合条件的查询记录  
  21.        * @param detachedCriteria  
  22.        * @param startResult  
  23.        * @param limitResult  
  24.        * @return  
  25.        */  
  26.   
  27.     public List listByConditions(final DetachedCriteria detachedCriteria,   
  28.             final int startResult, final int limitResult) {   
  29.   
  30.         return (List) getHibernateTemplate().execute(new HibernateCallback() {   
  31.             public Object doInHibernate(Session session)   
  32.                     throws HibernateException {   
  33.                 Criteria criteria = detachedCriteria   
  34.                         .getExecutableCriteria(session);   
  35.                 criteria.setFirstResult(startResult);   
  36.                 criteria.setMaxResults(limitResult);   
  37.                 return criteria.list();   
  38.             }   
  39.         }, true);   
  40.     }    
  41.     
  /**
	   * 获取符合查询条件的记录总数
	   * @param detachedCriteria  hibernate Criteria 查询对象,由service组装
	   * @return
	   */
  public Long getRecordCount(final DetachedCriteria detachedCriteria) {
		return (Long) getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException {
				Criteria criteria = detachedCriteria
						.getExecutableCriteria(session);
				long count = Long.parseLong((criteria.setProjection(Projections
						.rowCount()).uniqueResult()).toString());
				criteria.setProjection(null);
				return Long.valueOf("" + count);
			}
		}, true);
	}
/**
	   * 获取符合条件的查询记录
	   * @param detachedCriteria
	   * @param startResult
	   * @param limitResult
	   * @return
	   */

	public List listByConditions(final DetachedCriteria detachedCriteria,
			final int startResult, final int limitResult) {

		return (List) getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session)
					throws HibernateException {
				Criteria criteria = detachedCriteria
						.getExecutableCriteria(session);
				criteria.setFirstResult(startResult);
				criteria.setMaxResults(limitResult);
				return criteria.list();
			}
		}, true);
	} 
  

服务层:
Java代码 复制代码
  1. /**  
  2.      * 获取所有日志列表  
  3.      * @param startResult   查询记录起点  
  4.      * @param limitResult   简要列表每页最大记录数  
  5.      * @param sortRecord    简要列表排序字段名  
  6.      * @param dirRecord     简要列表排序类型 DESE/ASC  
  7.      * @return  
  8.      */  
  9. public JSONArray getAllLogs(String startResult,String limitResult,   
  10.               String sortRecord,String dirRecord) {   
  11.            
  12.         try {   
  13.             DetachedCriteria detachedCriteria = DetachedCriteria.forClass(TDeasLog.class);     
  14.             if(dirRecord.equals("ASC"))   
  15.                 detachedCriteria.addOrder(Order.asc(sortRecord));   
  16.             else  
  17.                 detachedCriteria.addOrder(Order.desc(sortRecord));   
  18.                  
  19.             Long count = logDAO.getRecordCount(detachedCriteria);//获取符合条件的记录总数       
  20.                  
  21.             List list = logDAO.listByConditions(detachedCriteria, Integer.parseInt(startResult),    
  22.                       Integer.parseInt(limitResult));//获取符合条件记录   
  23.             if(list.size()>0){   
  24.                 List jsonlist = new ArrayList();   
  25.                 Iterator it = list.iterator();   
  26.                 while (it.hasNext()){   
  27.                     Log log = (Log )it.next();   
  28.                     Map map = new HashMap();   
  29.                     map.put("taskId", log .getTaskId());   
  30.                     map.put("rwfssj", log .getRwfssj());   
  31.                     map.put("rwjssj", log .getRwjssj());   
  32.                             ....                                                       
  33.                     jsonlist.add(map);                 
  34.                 }   
  35.                 Map m = new  HashMap();   
  36.                 m.put("results", count.toString());   
  37.                 m.put("rows", jsonlist);   
  38.                    
  39.                 JSONArray jsonArray = JSONArray.fromObject(m);   
  40.                 return jsonArray;     
  41.             }else  
  42.                 return null;   
  43.         } catch (Exception e) {   
  44.             e.printStackTrace();   
  45.             return null;   
  46.         }   
  47.     }  
/**
	 * 获取所有日志列表
     * @param startResult   查询记录起点
     * @param limitResult   简要列表每页最大记录数
     * @param sortRecord    简要列表排序字段名
     * @param dirRecord     简要列表排序类型 DESE/ASC
	 * @return
	 */
public JSONArray getAllLogs(String startResult,String limitResult,
			  String sortRecord,String dirRecord) {
		
		try {
			DetachedCriteria detachedCriteria = DetachedCriteria.forClass(TDeasLog.class);  
			if(dirRecord.equals("ASC"))
				detachedCriteria.addOrder(Order.asc(sortRecord));
			else
				detachedCriteria.addOrder(Order.desc(sortRecord));
			  
			Long count = logDAO.getRecordCount(detachedCriteria);//获取符合条件的记录总数	  
			  
			List list = logDAO.listByConditions(detachedCriteria, Integer.parseInt(startResult), 
					  Integer.parseInt(limitResult));//获取符合条件记录
			if(list.size()>0){
				List jsonlist = new ArrayList();
				Iterator it = list.iterator();
				while (it.hasNext()){
					Log log = (Log )it.next();
					Map map = new HashMap();
					map.put("taskId", log .getTaskId());
					map.put("rwfssj", log .getRwfssj());
					map.put("rwjssj", log .getRwjssj());
							....													
					jsonlist.add(map);				
				}
				Map m = new  HashMap();
				m.put("results", count.toString());
				m.put("rows", jsonlist);
				
				JSONArray jsonArray = JSONArray.fromObject(m);
				return jsonArray;  
			}else
				return null;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}


action 代码:

Java代码 复制代码
  1.     
  2. public ActionForward getAllLogs(ActionMapping mapping, ActionForm form,   
  3.             HttpServletRequest request, HttpServletResponse response) {   
  4.            
  5.         String startResult = request.getParameter("start");   
  6.         String limitResult = request.getParameter("limit");   
  7.         String sortRecord = request.getParameter("sort");   
  8.         String dirRecord = request.getParameter("dir");   
  9.            
  10.         JSONArray jsonArray = this.getLogService().getAllLogs(startResult,limitResult,sortRecord,dirRecord);           
  11.            
  12.         if(jsonArray != null){   
  13.             String jsonstr = jsonArray.toString();   
  14.             //去除JSON对象前的[]     
  15.             String json = jsonstr.substring(1, jsonstr.length()-1);            
  16.             response.setContentType("text/json; charset=utf-8");    
  17.             try {   
  18.                 response.getWriter().print(json);   
  19.             } catch (IOException e) {   
  20.                 log.error("获取日志实例列表失败,异常:"+e.getMessage());   
  21.             }   
  22.         }else{//返回空数据,格式:{"rows":[],"results":"0"}   
  23.             List list = new ArrayList();   
  24.             Map map1 = new HashMap();   
  25.             list.add(map1);   
  26.             Map m = new  HashMap();   
  27.             m.put("results""0");   
  28.             m.put("rows", list);   
  29.             JSONArray json = JSONArray.fromObject(m);          
  30.             String jsonString = json.toString();   
  31.             String jsonstr =jsonString.substring(1, jsonString.length()-1);   
  32.             response.setContentType("text/json; charset=utf-8");    
  33.             try {   
  34.                 response.getWriter().print(jsonstr);   
  35.             } catch (IOException e) {   
  36.                 log.error("获取日志实例列表失败,异常:"+e.getMessage());   
  37.             }   
  38.         }          
  39.         return null;   
  40.     }  
 
public ActionForward getAllLogs(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		
		String startResult = request.getParameter("start");
		String limitResult = request.getParameter("limit");
		String sortRecord = request.getParameter("sort");
		String dirRecord = request.getParameter("dir");
		
		JSONArray jsonArray = this.getLogService().getAllLogs(startResult,limitResult,sortRecord,dirRecord);		
		
		if(jsonArray != null){
			String jsonstr = jsonArray.toString();
			//去除JSON对象前的[]  
			String json = jsonstr.substring(1, jsonstr.length()-1);			
			response.setContentType("text/json; charset=utf-8"); 
			try {
				response.getWriter().print(json);
			} catch (IOException e) {
				log.error("获取日志实例列表失败,异常:"+e.getMessage());
			}
		}else{//返回空数据,格式:{"rows":[],"results":"0"}
			List list = new ArrayList();
			Map map1 = new HashMap();
			list.add(map1);
			Map m = new  HashMap();
			m.put("results", "0");
			m.put("rows", list);
			JSONArray json = JSONArray.fromObject(m);		
			String jsonString = json.toString();
			String jsonstr =jsonString.substring(1, jsonString.length()-1);
			response.setContentType("text/json; charset=utf-8"); 
			try {
				response.getWriter().print(jsonstr);
			} catch (IOException e) {
				log.error("获取日志实例列表失败,异常:"+e.getMessage());
			}
		}		
		return null;
	}

开始无数据时怎么也不能显示PagingToolbar 的emptyMsg,后来发现空数据时组织格式错误,忘记去掉 [{"rows":[],"results":"0"}]这部分的“[]”,这个小问题折磨了俺好久,呵呵,要细心啊~!
JS代码:
Js代码 复制代码
  1.   var datastore = new Ext.data.Store({   
  2.        proxy: new Ext.data.HttpProxy({   
  3.            url: 'logManage.do?method=getAllLogs'  
  4.        }),   
  5.        reader: new Ext.data.JsonReader({   
  6.         root               : 'rows',   
  7.            totalProperty      : 'results',   
  8.            id: 'taskID'  
  9.        }, [   
  10.            {name: 'taskId'},   
  11.            {name: 'rwfssj'},   
  12.            {name: 'rwjssj'},   
  13.            ....   
  14.        ]),   
  15.         remoteSort: true  
  16.    });   
  17.    datastore.setDefaultSort('taskId','ASC');   
  18.    datastore.load({params:{start:0, limit:10}});   
  19.        
  20. var sm = new Ext.grid.CheckboxSelectionModel();   
  21. var colModel = new Ext.grid.ColumnModel([   
  22.     new Ext.grid.RowNumberer(),   
  23.     { header:'任务ID', width:100, sortable:true, locked:true, dataIndex:'taskId'},   
  24.     { header:'任务类型', width:100, sortable:true, locked:false, dataIndex:'rwlb'},   
  25.     { header:'任务状态', width:100, sortable:true, locked:false, dataIndex:'rwzt'},   
  26.     ......   
  27. ]);   
  28.        
  29. var LogGrid = new Ext.grid.GridPanel({   
  30.     ds                  : datastore,   
  31.     cm                  : colModel,   
  32.     sm                  : sm,   
  33.     id                  : 'LogGrid',   
  34.     title               : '日志列表',   
  35.     autoHeight          : true,   
  36.        width               : '100%',   
  37.        loadMask            : true,   
  38.      buttons            : [{   
  39.             text        : '查询',   
  40.             tooltip     : '日志查询',   
  41.             handler     : logSearch   
  42.      },{   
  43.             text        : '关闭',   
  44.             tooltip     : '关闭窗口',   
  45.             handler     : closeForm   
  46.      }],   
  47.        buttonAlign         : 'right',   
  48.        bbar                : new Ext.PagingToolbar({   
  49.            id              : 'pagingbar',   
  50.            pageSize        : 10,   
  51.            store           : datastore,   
  52.            displayInfo     : true  
  53.             })         
  54. });  
   var datastore = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({
            url: 'logManage.do?method=getAllLogs'
        }),
        reader: new Ext.data.JsonReader({
        	root               : 'rows',
            totalProperty      : 'results',
            id: 'taskID'
        }, [
            {name: 'taskId'},
            {name: 'rwfssj'},
            {name: 'rwjssj'},
            ....
        ]),
         remoteSort: true
    });
    datastore.setDefaultSort('taskId','ASC');
    datastore.load({params:{start:0, limit:10}});
		
	var sm = new Ext.grid.CheckboxSelectionModel();
	var colModel = new Ext.grid.ColumnModel([
		new Ext.grid.RowNumberer(),
		{ header:'任务ID', width:100, sortable:true, locked:true, dataIndex:'taskId'},
		{ header:'任务类型', width:100, sortable:true, locked:false, dataIndex:'rwlb'},
		{ header:'任务状态', width:100, sortable:true, locked:false, dataIndex:'rwzt'},
		......
	]);
		
	var LogGrid = new Ext.grid.GridPanel({
		ds					: datastore,
		cm					: colModel,
		sm					: sm,
		id                  : 'LogGrid',
		title				: '日志列表',
		autoHeight 		    : true,
        width               : '100%',
        loadMask            : true,
		 buttons            : [{
		        text	    : '查询',
				tooltip	    : '日志查询',
				handler   	: logSearch
		 },{
		        text	    : '关闭',
				tooltip	    : '关闭窗口',
				handler	    : closeForm
		 }],
        buttonAlign         : 'right',
        bbar                : new Ext.PagingToolbar({
            id              : 'pagingbar',
            pageSize        : 10,
            store           : datastore,
            displayInfo     : true
             })		
	});

搞定,收工....

你可能感兴趣的:(DAO,json,Hibernate,ext,Blog)