Spring jdbcTemplate + EasyUI 物理分页

用到的是SpringMVC + jdbcTemplate,前台是EasyUI,封装了下物理分页。

    这个是核心分页实体:

[java]  view plain copy
  1. import java.io.Serializable;  
  2. import java.util.List;  
  3. import java.util.Map;  
  4.   
  5. import org.apache.commons.lang.StringUtils;  
  6. import org.springframework.jdbc.core.JdbcTemplate;  
  7.   
  8.   
  9. /** 
  10.  * 分页实体 
  11.  * @author lyh 
  12.  * @version 2013-10-10 
  13.  * @see Pagination 
  14.  * @since 
  15.  */  
  16. public class Pagination implements Serializable  
  17. {  
  18.     /** 
  19.      * 序列号<br> 
  20.      */  
  21.     private static final long serialVersionUID = -2554565760258955645L;  
  22.   
  23.     /** 
  24.      * 每页显示的记录数 
  25.      */  
  26.     private int numPerPage;  
  27.   
  28.     /** 
  29.      * 记录总数 (命名必须为total 对应easyui分页) 
  30.      */  
  31.     private int total;  
  32.   
  33.     /** 
  34.      * 总页数 
  35.      */  
  36.     private int totalPages;  
  37.   
  38.     /** 
  39.      * 当前页码 
  40.      */  
  41.     private int currentPage;  
  42.   
  43.     /** 
  44.      * 记录起始行数 
  45.      */  
  46.     private int startIndex;  
  47.   
  48.     /** 
  49.      * 记录结束行数 
  50.      */  
  51.     private int lastIndex;  
  52.   
  53.     /** 
  54.      * 结果集存放List (命名必须为rows 对应easyui分页) 
  55.      */  
  56.     private List<Map<String,Object>> rows;  
  57.   
  58.   
  59.     /** 
  60.      * 构造函数 
  61.      * @param sql sql语句 
  62.      * @param currentPage 当前页码 
  63.      * @param numPerPage 每页显示记录数 
  64.      * @param jdbcTemplate JdbcTemplate实例 
  65.      */  
  66.     public Pagination(String sql, int currentPage, int numPerPage, JdbcTemplate jdbcTemplate)  
  67.     {  
  68.         if (jdbcTemplate == null)  
  69.         {  
  70.             throw new IllegalArgumentException(  
  71.                 "jdbcTemplate is null , pls initialize ... ");  
  72.         }  
  73.         else if (StringUtils.isBlank(sql))  
  74.         {  
  75.             throw new IllegalArgumentException("sql is blank , pls initialize ... ");  
  76.         }  
  77.         //设置每页显示记录数  
  78.         setNumPerPage(numPerPage);  
  79.   
  80.         //设置当前页数  
  81.         setCurrentPage(currentPage);  
  82.   
  83.         //计算总记录数SQL  
  84.         StringBuffer totalSQL = new StringBuffer(" select count(1) from ( ");  
  85.         totalSQL.append(sql);  
  86.         totalSQL.append(" ) ");  
  87.   
  88.         //总记录数  
  89.         setTotal(jdbcTemplate.queryForInt(totalSQL.toString()));  
  90.   
  91.         //计算总页数  
  92.         setTotalPages();  
  93.   
  94.         //计算起始行数  
  95.         setStartIndex();  
  96.   
  97.         //计算结束行数  
  98.         setLastIndex();  
  99.   
  100.         //拼装oracle的分页语句 (其他DB修改此处的分页关键词即可)  
  101.         StringBuffer paginationSQL = new StringBuffer(" select * from ( ");  
  102.         paginationSQL.append(" select row_limit.*,rownum rownum_ from ( ");  
  103.         paginationSQL.append(sql);  
  104.         paginationSQL.append(" ) row_limit where rownum <= " + lastIndex);  
  105.         paginationSQL.append(" ) where rownum_ > " + startIndex);  
  106.   
  107.         //装入结果集(key转为小写)  
  108.         setRows(ConvertMapkey.listKeyToLower(jdbcTemplate.queryForList(  
  109.             paginationSQL.toString())));  
  110.     }  
  111.   
  112.     /** 
  113.      * 根据总记录数和每页显示记录数 计算总页数 
  114.      *     
  115.      * @see 
  116.      */  
  117.     private void setTotalPages()  
  118.     {  
  119.         if (total % numPerPage == 0)  
  120.         {  
  121.             this.totalPages = total / numPerPage;  
  122.         }  
  123.         else  
  124.         {  
  125.             this.totalPages = (total / numPerPage) + 1;  
  126.         }  
  127.     }  
  128.   
  129.     /** 
  130.      * 根据当前页和每页显示记录条数 计算记录开始行数 
  131.      *     
  132.      * @see 
  133.      */  
  134.     private void setStartIndex()  
  135.     {  
  136.         this.startIndex = (currentPage - 1) * numPerPage;  
  137.     }  
  138.   
  139.     /** 
  140.      * 计算记录结束行数 
  141.      *     
  142.      * @see 
  143.      */  
  144.     private void setLastIndex()  
  145.     {  
  146.         if (total < numPerPage)  
  147.         {  
  148.             this.lastIndex = total;  
  149.         }  
  150.         else if ((total % numPerPage == 0)  
  151.                  || (total % numPerPage != 0 && currentPage < totalPages))  
  152.         {  
  153.             this.lastIndex = currentPage * numPerPage;  
  154.         }  
  155.         else if (total % numPerPage != 0 && currentPage == totalPages)  
  156.         {  
  157.             this.lastIndex = total;  
  158.         }  
  159.     }  
  160.   
  161.     //setter and getter  
  162.     public int getCurrentPage()  
  163.     {  
  164.         return currentPage;  
  165.     }  
  166.   
  167.     public void setCurrentPage(int currentPage)  
  168.     {  
  169.         this.currentPage = currentPage;  
  170.     }  
  171.   
  172.     public int getNumPerPage()  
  173.     {  
  174.         return numPerPage;  
  175.     }  
  176.   
  177.     public void setNumPerPage(int numPerPage)  
  178.     {  
  179.         this.numPerPage = numPerPage;  
  180.     }  
  181.   
  182.     public List<Map<String,Object>> getRows()  
  183.     {  
  184.         return rows;  
  185.     }  
  186.   
  187.     public void setRows(List<Map<String,Object>> rows)  
  188.     {  
  189.         this.rows = rows;  
  190.     }  
  191.   
  192.     public int getTotalPages()  
  193.     {  
  194.         return totalPages;  
  195.     }  
  196.   
  197.     public int getTotal()  
  198.     {  
  199.         return total;  
  200.     }  
  201.   
  202.     public void setTotal(int total)  
  203.     {  
  204.         this.total = total;  
  205.     }  
  206.   
  207.     public int getStartIndex()  
  208.     {  
  209.         return startIndex;  
  210.     }  
  211.   
  212.     public int getLastIndex()  
  213.     {  
  214.         return lastIndex;  
  215.     }  
  216.   
  217. }  


Map转化工具类:

[java]  view plain copy
  1. public class ConvertMapkey {  
  2.   
  3.     /** 
  4.      * 把map对象的key全部转为小写形式 
  5.      * @param map 
  6.      * @return 
  7.      */  
  8.     public static Map<String, Object> keyToLower(Map<String, Object> map) {  
  9.         Map<String, Object> r = new HashMap<String, Object>();  
  10.         if (map == null || map.size() == 0)  
  11.             return r;  
  12.         for (Map.Entry<String, Object> entry : map.entrySet()) {  
  13.             r.put(entry.getKey().toLowerCase(), entry.getValue());  
  14.         }  
  15.         return r;  
  16.     }  
  17.       
  18.     /** 
  19.      * 把list map中map对象的key全部转为小写形式 
  20.      * @param listmap 
  21.      * @return 
  22.      */  
  23.     public static List<Map<String, Object>> listKeyToLower(List<Map<String, Object>> listmap) {  
  24.         List<Map<String, Object>> r = new ArrayList<Map<String, Object>>();  
  25.         if (listmap == null || listmap.size() == 0)  
  26.             return r;  
  27.         for (Map<String, Object> map : listmap) {  
  28.             r.add(keyToLower(map));  
  29.         }  
  30.         return r;  
  31.     }  
  32. }  


DAO层 \ Service层:

[java]  view plain copy
  1. return new Pagination(sqlFetchRows, page, rows, jdbcTemplate);  

Controller层:

[java]  view plain copy
  1.  @RequestMapping(value = "/list_school")  
  2. @ResponseBody  
  3. public Pagination listSchool(HttpServletRequest request) {  
  4.       
  5.     Pagination p = null;  
  6.     try {  
  7.           
  8.         int page = Integer.parseInt(request.getParameter("page"));  
  9.         int rows = Integer.parseInt(request.getParameter("rows"));  
  10.           
  11.         String school_code = request.getParameter("s_school_code");  
  12.         String school_name = request.getParameter("s_school_name");  
  13.           
  14.         //page:当前页   rows:每页显示记录条数  区别结果集存放List-rows  
  15.         p  = schoolService.pageData(page, rows, school_id, school_code, school_name);             
  16.           
  17.     } catch (Exception e) {  
  18.         logger.error(e);  
  19.     }  
  20.     return p;  
  21. }  

注意:Controller返回的 Pagination实体借助jackson会转为JSON(故实体中一定不能含有jdbcTemplate字段,jdbcTemplate只能通过方法形式注入),然后在EasyUi中展示。

<[org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor] - Written [{twokey=twovalue, onekey=onevalue}] as "application/json;charset=UTF-8" using [org.springframework.http.converter.json.MappingJacksonHttpMessageConverter@8f3da5]>


通过FireFox 可以发现上述返回的分页实体的JSON。

JS部分:

[javascript]  view plain copy
  1.     // 查询  
  2. ('#btn_02010100').click(function() {  
  3. $('#basedg').datagrid('load');  
  4. );  

[javascript]  view plain copy
  1.     $('#basedg').datagrid({  
  2.         animate: true,        //是否动画展开折叠  
  3.         checkbox: true//全选复选框  
  4.         checkOnSelect: true//选中复选框的同时选中行  
  5.         selectOnCheck: true//选中行的同时选中复选框  
  6.         singleSelect: false//是否单选  
  7.         collapsible: true,    //是否可折叠  
  8.         height: 'auto',  //自动高度  
  9.         iconCls: 'icon-save',  //样式图标  
  10.         idField: 'school_id',   //主索引,唯一标识字段  
  11.         loadMsg: '数据载入中,请稍候......',  
  12.         maximizable: true,  
  13.         nowrap: true,  //截断内文  
  14.         pagination: true//分页  
  15.         pageList: [10,15,20,25,30],  
  16.         rownumbers: true,   //是否显示列数,  
  17.         url: basePath + '/school/list_school',  
  18.         frozenColumns: [[  
  19.             {field:'ck',checkbox:true},  
  20.             {field:'school_id',title:'唯一id',hidden:true},  
  21.             {field:'school_code',title:'学校代码',width:80},  
  22.             {field:'school_name',title:'学校名称',width:200}  
  23.         ]],  
  24.         columns: [[  
  25.             {field:'schooling_length',title:'学制',width:100},  
  26.             {field:'telephone',title:'联系电话',width:120},  
  27.             {field:'school_address',title:'学校地址',width:300},  
  28.             {field:'establishment_date',title:'建校年月',width:80,  
  29.                 formatter:function (value) {  
  30.                     return value == null ? '' : (new Date(value).format('yyyy-MM-dd'));  
  31.                 }  
  32.             }  
  33.         ]],  
  34.         onBeforeLoad: function (param) {  
  35.             param.s_school_code = $('#s_school_code').searchbox('getValue');  
  36.             param.s_school_name = $('#s_school_name').searchbox('getValue');  
  37.         }  
  38.     });  
  39. }  

JSP页面:

[html]  view plain copy
  1. <table id="basedg" toolbar="#toolbar" pagination="true"></table>  
  2. <div id="toolbar">  
  3.         <div id="searchbar">  
  4.             <table cellspacing="0" cellpadding="0">  
  5.                 <tr>  
  6.                     <td>查询条件:</td>  
  7.                     <td>  
  8.                         <input id="s_school_code" class="easyui-searchbox" data-options="prompt:'学校代码'"></input>  
  9.                     </td>  
  10.                     <td>  
  11.                         <input id="s_school_name" class="easyui-searchbox" data-options="prompt:'学校名称'"></input>  
  12.                     </td>  
  13.                 </tr>  
  14.         </table>  
  15.         </div>  
  16.         <a href="javascript:void(0)" id="btn_02010100" class="easyui-linkbutton" iconCls="icon-search" plain="true">查询</a>  
  17. </div>  

最终效果:


每次查询时的触发SQL如下:

[java]  view plain copy
  1. log Begining method: com.ruhuiyun.studentmanager.service.SchoolService.pageData  
  2. 2013-10-11 10:40:18,345 [qtp14565508-22] DEBUG [org.springframework.jdbc.core.JdbcTemplate] - Executing SQL query [ select count(1) from ( SELECT school_id, school_code, school_name, schooling_length, school_address, telephone, establishment_date FROM T_SCHOOL WHERE 1 = 1 AND instr(school_name, '无锡') > 0 ) ]  
  3. 2013-10-11 10:40:18,349 [qtp14565508-22] DEBUG [org.springframework.jdbc.core.JdbcTemplate] - Executing SQL query [ select * from (  select row_limit.*,rownum rownum_ from ( SELECT school_id, school_code, school_name, schooling_length, school_address, telephone, establishment_date FROM T_SCHOOL WHERE 1 = 1 AND instr(school_name, '无锡') > 0 ) row_limit where rownum <= 2 ) where rownum_ > 0]  
  4. 2013-10-11 10:40:18,353 [qtp14565508-22] INFO  [com.ruhuiyun.studentmanager.aop.LogAdvice] - log Ending method: com.ruhuiyun.studentmanager.service.SchoolService.pageData  


转自:http://blog.youkuaiyun.com/will_awoke/article/details/12610887
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值