com.baidu.dpop.ctp.common.mybatis.page.PageHelper.java Source code

Java tutorial

Introduction

Here is the source code for com.baidu.dpop.ctp.common.mybatis.page.PageHelper.java

Source

/*
   The MIT License (MIT)
    
   Copyright (c) 2014 abel533@gmail.com
    
   Permission is hereby granted, free of charge, to any person obtaining a copy
   of this software and associated documentation files (the "Software"), to deal
   in the Software without restriction, including without limitation the rights
   to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
   copies of the Software, and to permit persons to whom the Software is
   furnished to do so, subject to the following conditions:
    
   The above copyright notice and this permission notice shall be included in
   all copies or substantial portions of the Software.
    
   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
   AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
   OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
   THE SOFTWARE.
*/

package com.baidu.dpop.ctp.common.mybatis.page;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * Mybatis - 
 *
 * @author liuzh/abel533/isea533
 * @version 3.3.0
 *          ? : http://git.oschina.net/free/Mybatis_PageHelper
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
@Intercepts(@Signature(type = Executor.class, method = "query", args = { MappedStatement.class, Object.class,
        RowBounds.class, ResultHandler.class }))
public class PageHelper implements Interceptor {

    private static final ThreadLocal<Page> LOCAL_PAGE = new ThreadLocal<Page>();
    //sql
    private SqlUtil SQLUTIL;
    //RowBounds?offsetPageNum - ?
    private boolean offsetAsPageNum = false;
    //RowBounds?count - ?
    private boolean rowBoundsWithCount = false;
    //truepagesize0RowBoundslimit=0?
    private boolean pageSizeZero = false;
    //??
    private boolean reasonable = false;
    //params?
    private static Map<String, String> PARAMS = new HashMap<String, String>(5);
    //request?
    private static Boolean hasRequest;
    private static Class<?> requestClass;
    private static Method getParameter;

    /**
     * 
     *
     * @param pageNum  ?
     * @param pageSize ??
     */
    public static void startPage(int pageNum, int pageSize) {
        startPage(pageNum, pageSize, true);
    }

    /**
     * 
     *
     * @param pageNum  ?
     * @param pageSize ??
     * @param count    ?count
     */
    public static void startPage(int pageNum, int pageSize, boolean count) {
        startPage(pageNum, pageSize, count, null);
    }

    /**
     * 
     *
     * @param pageNum    ?
     * @param pageSize   ??
     * @param count      ?count
     * @param reasonable ??,null?
     */
    public static void startPage(int pageNum, int pageSize, boolean count, Boolean reasonable) {
        startPage(pageNum, pageSize, count, reasonable, null);
    }

    /**
     * 
     *
     * @param pageNum      ?
     * @param pageSize     ??
     * @param count        ?count
     * @param reasonable   ??,null?
     * @param pageSizeZero truepageSize=0false,null?
     */
    public static void startPage(int pageNum, int pageSize, boolean count, Boolean reasonable,
            Boolean pageSizeZero) {
        Page page = new Page(pageNum, pageSize, count);
        page.setReasonable(reasonable);
        page.setPageSizeZero(pageSizeZero);
        LOCAL_PAGE.set(page);
    }

    /**
     * 
     *
     * @param params ?MapServletRequest
     */
    public static void startPage(Object params) {
        int pageNum = 0;
        int pageSize = 0;
        try {
            pageNum = Integer.parseInt(String.valueOf(getParamValue(params, "pageNum", true)));
            pageSize = Integer.parseInt(String.valueOf(getParamValue(params, "pageSize", true)));
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("???!");
        }
        Object _count = getParamValue(params, "count", false);
        boolean count = true;
        if (_count != null) {
            count = Boolean.valueOf(String.valueOf(_count));
        }
        Page page = new Page(pageNum, pageSize, count);
        Object reasonable = getParamValue(params, "reasonable", false);
        if (reasonable != null) {
            page.setReasonable(Boolean.valueOf(String.valueOf(reasonable)));
        }
        Object pageSizeZero = getParamValue(params, "pageSizeZero", false);
        if (pageSizeZero != null) {
            page.setPageSizeZero(Boolean.valueOf(String.valueOf(pageSizeZero)));
        }
        LOCAL_PAGE.set(page);
    }

    /**
     * ??
     *
     * @param params
     * @param paramName
     * @param required
     * @return
     */
    private static Object getParamValue(Object params, String paramName, boolean required) {
        if (params == null) {
            throw new NullPointerException("?params?!");
        }
        Object value = null;
        if (params instanceof Map) {
            if (((Map) params).containsKey(PARAMS.get(paramName))) {
                value = ((Map) params).get(PARAMS.get(paramName));
            }
        } else {
            if (hasRequest == null) {
                try {
                    requestClass = Class.forName("javax.servlet.ServletRequest");
                    getParameter = requestClass.getMethod("getParameter", String.class);
                    hasRequest = true;
                } catch (NoSuchMethodException e) {
                    hasRequest = false;
                } catch (ClassNotFoundException e) {
                    hasRequest = false;
                }
            }
            if (hasRequest) {
                try {
                    if (requestClass.isAssignableFrom(params.getClass())) {
                        value = getParameter.invoke(params, PARAMS.get(paramName));
                    } else {
                        throw new IllegalArgumentException(
                                "?params?MapServletRequest!");
                    }
                } catch (IllegalArgumentException e) {
                    throw e;
                } catch (Exception e) {
                    //
                }
            } else {
                throw new IllegalArgumentException(
                        "?params?MapServletRequest!");
            }
        }
        if (required && value == null) {
            throw new RuntimeException("??:" + paramName);
        }
        return value;
    }

    /**
     * ??
     *
     * @param rowBounds RowBounds?
     * @return Page
     */
    private Page getPage(RowBounds rowBounds) {
        Page page = LOCAL_PAGE.get();
        //??
        LOCAL_PAGE.remove();
        if (page == null) {
            if (offsetAsPageNum) {
                page = new Page(rowBounds.getOffset(), rowBounds.getLimit(), rowBoundsWithCount);
            } else {
                page = new Page(rowBounds, rowBoundsWithCount);
            }
        }
        //??
        if (page.getReasonable() == null) {
            page.setReasonable(reasonable);
        }
        //truepagesize0RowBoundslimit=0?
        if (page.getPageSizeZero() == null) {
            page.setPageSizeZero(pageSizeZero);
        }
        return page;
    }

    /**
     * Mybatis
     *
     * @param invocation ?
     * @return 
     * @throws Throwable 
     */
    public Object intercept(Invocation invocation) throws Throwable {

        final Object[] args = invocation.getArgs();
        RowBounds rowBounds = (RowBounds) args[2];

        if (LOCAL_PAGE.get() == null && rowBounds == RowBounds.DEFAULT) {
            return invocation.proceed();
        } else {

            //?ms
            MappedStatement ms = (MappedStatement) args[0];

            //RowBounds-?Mybatis
            args[2] = RowBounds.DEFAULT;
            //?
            Page page = getPage(rowBounds);
            //pageSizeZero
            if ((page.getPageSizeZero() != null && page.getPageSizeZero()) && page.getPageSize() == 0) {
                //?
                Object result = invocation.proceed();
                //?
                page.addAll((List) result);
                //
                page.setPageNum(1);
                //?pageSize=total
                page.setPageSize(page.size());
                //??total
                page.setTotal(page.size());
                //?Page - ???
                return page;
            }
            SqlSource sqlSource = ((MappedStatement) args[0]).getSqlSource();
            //?total??count
            if (page.isCount()) {
                //?MappedStatement?qs
                SQLUTIL.processCountMappedStatement(ms, sqlSource, args);
                //
                Object result = invocation.proceed();
                //
                page.setTotal((Integer) ((List) result).get(0));
                if (page.getTotal() == 0) {
                    return page;
                }
            }
            //pageSize>0pageSize<=0???count
            if (page.getPageSize() > 0 && ((rowBounds == RowBounds.DEFAULT && page.getPageNum() > 0)
                    || rowBounds != RowBounds.DEFAULT)) {
                //?MappedStatement?qs
                SQLUTIL.processPageMappedStatement(ms, sqlSource, page, args);
                //
                Object result = invocation.proceed();
                //?
                page.addAll((List) result);
            }
            //
            return page;
        }
    }

    /**
     * ?Executor
     *
     * @param target
     * @return
     */
    public Object plugin(Object target) {
        if (target instanceof Executor) {
            return Plugin.wrap(target, this);
        } else {
            return target;
        }
    }

    /**
     * 
     *
     * @param p 
     */
    public void setProperties(Properties p) {
        //?
        String dialect = p.getProperty("dialect");
        SQLUTIL = new SqlUtil(dialect);
        //offsetPageNum
        String offsetAsPageNum = p.getProperty("offsetAsPageNum");
        this.offsetAsPageNum = Boolean.parseBoolean(offsetAsPageNum);
        //RowBounds???count
        String rowBoundsWithCount = p.getProperty("rowBoundsWithCount");
        this.rowBoundsWithCount = Boolean.parseBoolean(rowBoundsWithCount);
        //truepagesize0RowBoundslimit=0?
        String pageSizeZero = p.getProperty("pageSizeZero");
        this.pageSizeZero = Boolean.parseBoolean(pageSizeZero);
        //??true?????false??
        String reasonable = p.getProperty("reasonable");
        this.reasonable = Boolean.parseBoolean(reasonable);
        //?
        PARAMS.put("pageNum", "pageNum");
        PARAMS.put("pageSize", "pageSize");
        PARAMS.put("count", "countSql");
        PARAMS.put("reasonable", "reasonable");
        PARAMS.put("pageSizeZero", "pageSizeZero");
        String params = p.getProperty("params");
        if (params != null && params.length() > 0) {
            String[] ps = params.split("[;|,|&]");
            for (String s : ps) {
                String[] ss = s.split("[=|:]");
                if (ss.length == 2) {
                    PARAMS.put(ss[0], ss[1]);
                }
            }
        }
    }
}