mybatis分页插件

MyBatis allows you to intercept calls to at certain points within the execution of a mapped statement.
By default, MyBatis allows plug-ins to intercept method calls of:
• Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)
• ParameterHandler (getParameterObject, setParameters)
• ResultSetHandler (handleResultSets, handleOutputParameters)
• StatementHandler (prepare, parameterize, batch, update, query)

1、mybatis-config.xml配置文件添加

        <plugins>
            <plugin interceptor="org.flex.examples.common.PaginationPlugin">
                <property name="dialectClass" value="org.flex.examples.dialect.MySql5Dialect" />
            </plugin>
        </plugins>

2、分页拦截器编写

@Intercepts({ @Signature(type = RoutingStatementHandler.class, method = "prepare", args = { Connection.class }) })
public class PaginationPlugin implements Interceptor {
 private static final Logger logger = LoggerFactory
            .getLogger(PaginationPlugin.class);
    /**
     *
     */
    public Object intercept(Invocation invocation) throws Throwable {

        StatementHandler stmtHandler = (StatementHandler) invocation
                .getTarget();
        BoundSql boundSql = stmtHandler.getBoundSql();
        MetaObject metaObject = SystemMetaObject.forObject(
                stmtHandler);
        RowBounds rowBounds = (RowBounds) metaObject
                .getValue("delegate.rowBounds");
        if (rowBounds == null || rowBounds == RowBounds.DEFAULT) {
            return invocation.proceed();
        }
        Dialect dialect = null;
        //方言类
        dialect = (Dialect) Class.forName(dialectClass).newInstance();

        String originalSql = (String) metaObject
                .getValue("delegate.boundSql.sql");

        metaObject.setValue("delegate.boundSql.sql", dialect
                .getLimitString(originalSql, rowBounds.getOffset(),
                        rowBounds.getLimit()));

        metaObject.setValue("delegate.rowBounds.offset",
                RowBounds.NO_ROW_OFFSET);

        metaObject.setValue("delegate.rowBounds.limit",
                RowBounds.NO_ROW_LIMIT);
        System.out.println(boundSql.getSql());
        if (logger.isDebugEnabled()) {
            logger.info("生成分页SQL : " + boundSql.getSql());
        }
        return invocation.proceed();
    }

    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    public void setProperties(Properties properties) {
        dialectClass=properties.getProperty("dialectClass");
    }
    private String dialectClass;
}

拦截RoutingStatementHandler类的prepare方法,通过反射获取RowBounds和sql

结合dialectClass,修改sql添加分页语句块,实现数据库分页。

dialectClass类是根据各个数据库的不同编写,举个例子MySQL分页是limit 1,20,

而Oracle分页是采用rownum来进行分页。

3、service层调用示例

    public PageResult getUserPagination(User user,PageResult pageResult){
        int offset=(pageResult.getPageNo()-1)*pageResult.getPageSize();
        int limit=pageResult.getPageSize();
        RowBounds rb=new RowBounds(offset,limit);
        List<Map<String,Object>> dataList=userMapper.getUserPagination(user,rb);
        int total=userMapper.getUserTotal(user);
        pageResult.setDataList(dataList);
        pageResult.setTotal(total);
        return pageResult;
    }
分页分成2个部分,一个是取得相应页号的记录集,另一个是取得总的一个记录数。

取得总记录数这个数据查询暂时是另外写的一个sql

总结:本文也参照了网上多个大神的版本,个人感觉这样实现是比较简单

猜你喜欢

转载自qryt520.iteye.com/blog/2191260