《mybatis下的分页支持所有的数据库》由会员分享,可在线阅读,更多相关《mybatis下的分页支持所有的数据库(11页珍藏版)》请在金锄头文库上搜索。
1、文档供参考,可复制、编制,期待您的好评与关注! 大 家都知道,mybatis的自带分页方法只是逻辑分 页,如果数据量很大,内存一定会溢出,不知道为什么开源组织不在里面集成hibernate的物理分页处理方法!在不修改mybatis源代码的情况下, 应该怎么使mybatis支持物理分页呢?参考了网上的一些信息,有了下面的解决方法:以oracle为例子1.把hibernate下的dialect包全部拷贝到mybatis包的jdbc目录下,如下图所示:2.定义一个ResultSetHandler Interceptorpackage cn.machi.utils;import java.sql.St
2、atement;import java.util.Properties;import org.apache.ibatis.executor.resultset.FastResultSetHandler;import org.apache.ibatis.executor.resultset.ResultSetHandler;import org.apache.ibatis.plugin.Interceptor;import org.apache.ibatis.plugin.Intercepts;import org.apache.ibatis.plugin.Invocation;import o
3、rg.apache.ibatis.plugin.Plugin;import org.apache.ibatis.plugin.Signature;import org.apache.ibatis.session.RowBounds;Intercepts(Signature(type= ResultSetHandler.class, method = handleResultSets, args = Statement.class)public class DiclectResultSetHandlerInterceptor implements Interceptor public Objec
4、t intercept(Invocation invocation) throws Throwable FastResultSetHandler resultSet = (FastResultSetHandler)invocation.getTarget(); RowBounds rowBounds = (RowBounds)ReflectUtil.getFieldValue(resultSet, rowBounds); if (rowBounds.getLimit() 0 & rowBounds.getLimit() 0 & rowBounds.getLimit() RowBounds.NO
5、_ROW_LIMIT) BoundSql boundSql = statement.getBoundSql(); String sql = boundSql.getSql(); OracleDialect dialect = (OracleDialect)Class.forName(DIALECT) .newInstance(); sql = dialect.getLimitString(sql, rowBounds.getOffset(), rowBounds.getLimit(); ReflectUtil.setFieldValue(boundSql, sql, sql); return
6、invocation.proceed(); public Object plugin(Object target) return Plugin.wrap(target, this); public void setProperties(Properties properties) 4.定义工具类ReflectUtilpackage cn.machi.utils;import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;impo
7、rt java.lang.reflect.Modifier;import org.apache.log4j.Logger;public class ReflectUtil private static Logger log = Logger.getLogger(ReflectUtil.class); private static Object operate(Object obj, String fieldName, Object fieldVal, String type) Object ret = null; try / 获得对象类型 Class classType = obj.getClass(); / 获得对象的所有属性 Field fields = classType.getDeclaredFields(); for (int i = 0; i fields.length; i+) Field field = fieldsi; if (field.getName().equals(fieldName) String firstLetter = fieldName.substring(0, 1) .toUpperCase(); / 获得和属性对应的getXXX()方法的名字 if (set.equals(type) String set