对IBatis分页的改进,使ibatis支持hibernate式的物理分页

 

      公司的大部分项目都开始使用IBatis作为O/R Mapping了,但是在使用的过程中也发现了很多不方便和存在争议的地方,其中一个不方便的地方就是分页,目前的处理方式都是在sqlMap中写针对特定数据库的物理分页Sql语句,对于oracle数据库都是在分页的sql语句里面加上三层嵌套的sql语句,想了很多办法,都没能很好的避免这个问题,无意间在javaeye上看到了《使ibatis支持hibernate式的物理分页》这篇文章,可点进去已经被删除了,幸好google了一下有很多人已经收藏了,这里转载一下,以便再找不到了.

 

转载地址:http://www.blogjava.net/libin2722/articles/192504.html

 

一直以来ibatis的分页都是通过滚动ResultSet实现的,应该算是逻辑分页吧。逻辑分页虽然能很干净地独立于特定数据库,但效率在多数情况下不及特定数据库支持的物理分页,而hibernate的分页则是直接组装sql,充分利用了特定数据库的分页机制,效率相对较高。本文讲述的就是如何在不重新编译ibatis源码的前提下,为ibatis引入hibernate式的物理分页机制。

基本思路就是找到ibatis执行sql的地方,截获sql并重新组装sql。通过分析ibatis源码知道,最终负责执行sql的类是 com.ibatis.sqlmap.engine.execution.SqlExecutor,此类没有实现任何接口,这多少有点遗憾,因为接口是相对稳定契约,非大的版本更新,接口一般是不会变的,而类就相对易变一些,所以这里的代码只能保证对当前版本(2.1.7)的ibatis有效。下面是 SqlExecutor执行查询的方法:

Java代码 
  1. /** 
  2.    * Long form of the method to execute a query 
  3.    * 
  4.    * @param request - the request scope 
  5.    * @param conn - the database connection 
  6.    * @param sql - the SQL statement to execute 
  7.    * @param parameters - the parameters for the statement 
  8.    * @param skipResults - the number of results to skip 
  9.    * @param maxResults - the maximum number of results to return 
  10.    * @param callback - the row handler for the query 
  11.    * 
  12.    * @throws SQLException - if the query fails 
  13.    */  
  14.   public void executeQuery(RequestScope request, Connection conn, String sql, Object[] parameters,  
  15.                            int skipResults, int maxResults, RowHandlerCallback callback)  
  16.       throws SQLException {  
  17.     ErrorContext errorContext = request.getErrorContext();  
  18.     errorContext.setActivity("executing query");  
  19.     errorContext.setObjectId(sql);  
  20.   
  21.     PreparedStatement ps = null;  
  22.     ResultSet rs = null;  
  23.   
  24.     try {  
  25.       errorContext.setMoreInfo("Check the SQL Statement (preparation failed).");  
  26.   
  27.       Integer rsType = request.getStatement().getResultSetType();  
  28.       if (rsType != null) {  
  29.         ps = conn.prepareStatement(sql, rsType.intValue(), ResultSet.CONCUR_READ_ONLY);  
  30.       } else {  
  31.         ps = conn.prepareStatement(sql);  
  32.       }  
  33.   
  34.       Integer fetchSize = request.getStatement().getFetchSize();  
  35.       if (fetchSize != null) {  
  36.         ps.setFetchSize(fetchSize.intValue());  
  37.       }  
  38.   
  39.       errorContext.setMoreInfo("Check the parameters (set parameters failed).");  
  40.       request.getParameterMap().setParameters(request, ps, parameters);  
  41.   
  42.       errorContext.setMoreInfo("Check the statement (query failed).");  
  43.   
  44.       ps.execute();  
  45.       rs = getFirstResultSet(ps);  
  46.   
  47.       if (rs != null) {  
  48.         errorContext.setMoreInfo("Check the results (failed to retrieve results).");  
  49.         handleResults(request, rs, skipResults, maxResults, callback);  
  50.       }  
  51.   
  52.       // clear out remaining results  
  53.       while (ps.getMoreResults());  
  54.   
  55.     } finally {  
  56.       try {  
  57.         closeResultSet(rs);  
  58.       } finally {  
  59.         closeStatement(ps);  
  60.       }  
  61.     }  
  62.   
  63.   }  

 

其中handleResults(request, rs, skipResults, maxResults, callback)一句用于处理分页,其实此时查询已经执行完毕,可以不必关心handleResults方法,但为清楚起见,下面来看看 handleResults的实现:

Java代码 
  1. private void handleResults(RequestScope request, ResultSet rs, int skipResults, int maxResults, RowHandlerCallback callback) throws SQLException {  
  2.     try {  
  3.       request.setResultSet(rs);  
  4.       ResultMap resultMap = request.getResultMap();  
  5.       if (resultMap != null) {  
  6.         // Skip Results  
  7.         if (rs.getType() != ResultSet.TYPE_FORWARD_ONLY) {  
  8.           if (skipResults > 0) {  
  9.             rs.absolute(skipResults);  
  10.           }  
  11.         } else {  
  12.           for (int i = 0; i < skipResults; i++) {  
  13.             if (!rs.next()) {  
  14.               break;  
  15.             }  
  16.           }  
  17.         }  
  18.   
  19.         // Get Results  
  20.         int resultsFetched = 0;  
  21.         while ((maxResults == SqlExecutor.NO_MAXIMUM_RESULTS || resultsFetched < maxResults) && rs.next()) {  
  22.           Object[] columnValues = resultMap.resolveSubMap(request, rs).getResults(request, rs);  
  23.           callback.handleResultObject(request, columnValues, rs);  
  24.           resultsFetched++;  
  25.         }  
  26.       }  
  27.     } finally {  
  28.       request.setResultSet(null);  
  29.     }  
  30.   }  

 

此处优先使用的是ResultSet的absolute方法定位记录,是否支持absolute取决于具体数据库驱动,但一般当前版本的数据库都支持该方法,如果不支持则逐条跳过前面的记录。由此可以看出如果数据库支持absolute,则ibatis内置的分页策略与特定数据库的物理分页效率差距就在于物理分页查询与不分页查询在数据库中的执行效率的差距了。因为查询执行后读取数据前数据库并未把结果全部返回到内存,所以本身在存储占用上应该差距不大,如果都使用索引,估计执行速度也差不太多。

继续我们的话题。其实只要在executeQuery执行前组装sql,然后将其传给 executeQuery,并告诉handleResults我们不需要逻辑分页即可。拦截executeQuery可以采用aop动态实现,也可直接继承SqlExecutor覆盖executeQuery来静态地实现,相比之下后者要简单许多,而且由于SqlExecutor没有实现任何接口,比较易变,动态拦截反到增加了维护的工作量,所以我们下面来覆盖executeQuery:

Java代码 
  1. package com.aladdin.dao.ibatis.ext;  
  2.   
  3. import java.sql.Connection;  
  4. import java.sql.SQLException;  
  5.   
  6. import org.apache.commons.logging.Log;  
  7. import org.apache.commons.logging.LogFactory;  
  8.   
  9. import com.aladdin.dao.dialect.Dialect;  
  10. import com.ibatis.sqlmap.engine.execution.SqlExecutor;  
  11. import com.ibatis.sqlmap.engine.mapping.statement.RowHandlerCallback;  
  12. import com.ibatis.sqlmap.engine.scope.RequestScope;  
  13.   
  14. public class LimitSqlExecutor extends SqlExecutor {  
  15.   
  16.     private static final Log logger = LogFactory.getLog(LimitSqlExecutor.class);  
  17.       
  18.     private Dialect dialect;  
  19.   
  20.     private boolean enableLimit = true;  
  21.   
  22.     public Dialect getDialect() {  
  23.         return dialect;  
  24.     }  
  25.   
  26.     
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值