mybatis pagehelp

简介:     使用 github 上 分页 插件 com.github.pagehelper pagehelper     在mybatis-config.

 

 

使用 github 上 分页 插件

<dependency>
			<groupId>com.github.pagehelper</groupId>
			<artifactId>pagehelper</artifactId>
		</dependency>

 

 

在mybatis-config.xml 中添加 plugin

 

 <plugin interceptor="com.curiousby.util.PagePluginWrapper">
			<property name="dialect" value="mysql"/>
			<property name="pageSqlId" value=".*listPage.*"/>
		</plugin>

 

配置datasources

<!-- 配置mybitasSqlSessionFactoryBean -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="configLocation" value="classpath:mybatis-config.xml"></property>
		<property name="typeAliasesPackage" value="com.curiousby.entity"></property>
		<property name="mapperLocations" value="classpath:mapping/*.xml"></property>
	</bean>

 

 

package com.curiousby.util;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Properties;

import javax.xml.bind.PropertyException;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.springframework.util.StringUtils;

import com.github.pagehelper.PageHelper;

/**
 * @see com.curiosuby.util.PagePluginWrapper
 * @author baoyou E-mail:curiousby@163.com
 * @version 2017年3月14日 下午5:52:11
 * desc:
 */
@Intercepts(@Signature(type = Executor.class, method = "query", args = { MappedStatement.class,
        Object.class, RowBounds.class, ResultHandler.class }))
public class PagePluginWrapper extends PageHelper {

    // private static final Logger log = LoggerFactory.getLogger(PagePluginWrapper.class);

    private String pageSqlId = "";

    /**
     * 
     */
    public Object intercept(Invocation ivk) throws Throwable {
        // log.info("pageSqlId:" + pageSqlId);
        if (ivk.getTarget() instanceof Executor) {
            return this.invokePageIntercept(ivk);
        }
        return ivk.proceed();
    }

    private Object invokePageIntercept(Invocation ivk) throws Throwable {
        // log.info("invokePageIntercept");
        MappedStatement mappedStatement = (MappedStatement) ivk.getArgs()[0];
        // log.info("mappedStatement id:" + mappedStatement.getId());
        if (mappedStatement.getId().matches(pageSqlId)) { // 拦截需要分页的SQL
            Object parameter = ivk.getArgs()[1];
            BoundSql boundSql = mappedStatement.getSqlSource().getBoundSql(parameter);
            Object parameterObject = boundSql.getParameterObject();// 分页SQL<select>中parameterType属性对应的实体参数,即Mapper接口中执行分页方法的参数,该参数不得为空
            if (parameterObject == null) {
                throw new NullPointerException("parameterObject尚未实例化!");
            } else {
                boolean pagable = setPage(parameterObject);
                if (pagable) {
                    Object obj = super.intercept(ivk);
                    if (obj instanceof com.github.pagehelper.Page) {
                        com.github.pagehelper.Page page = (com.github.pagehelper.Page) obj;
                        this.setTotalPage(parameterObject, page);
                        return page.getResult();
                    }
                }
            }
        }
        return ivk.proceed();
    }

    private void setTotalPage(Object parameterObject, com.github.pagehelper.Page resultPage)
            throws Throwable {
        //log.info("setTotalPage");
        Page page = null;
        Integer totalResult = Integer.valueOf("" + resultPage.getTotal());
        if (parameterObject instanceof Page) { // 参数就是Page实体
            page = (Page) parameterObject;
            page.setTotalResult(totalResult);
        } else if (parameterObject instanceof java.util.HashMap) { // 参数是HashMap
            HashMap<Object, Object> parms = (HashMap<Object, Object>) parameterObject;
            parms.put("count", totalResult);
        } else { // 参数为某个实体,该实体拥有Page属性
            Field pageField = ReflectHelper.getFieldByFieldName(parameterObject, "page");
            if (pageField != null) {
                page = (Page) ReflectHelper.getValueByFieldName(parameterObject, "page");
                if (page == null) {
                    page = new Page();
                }
                page.setTotalResult(totalResult);
                ReflectHelper.setValueByFieldName(parameterObject, "page", page); // 通过反射,对实体对象设置分页对象
            } else {
                throw new NoSuchFieldException(parameterObject.getClass().getName()
                        + "不存在 page 属性!");
            }
        }
    }

    /**
     * 是否有分页参数,没有则不分页
     * @param parameterObject
     * @return
     * @throws Throwable
     */
    private boolean setPage(Object parameterObject) throws Throwable {
        // log.info("setpage");
        Page page = null;
        Integer pageNo = 1;
        Integer maxRow = 10;
        if (parameterObject instanceof Page) { // 参数就是Page实体
            page = (Page) parameterObject;
            pageNo = page.getCurrentPageDef();
            maxRow = page.getShowCount();
        } else if (parameterObject instanceof java.util.HashMap) { // 参数是HashMap
            HashMap<Object, Object> parms = (HashMap<Object, Object>) parameterObject;
            if (!parms.containsKey("pageNo") || !parms.containsKey("maxRow")) {
                return false;
            }
            pageNo = (Integer) parms.get("pageNo");
            maxRow = (Integer) parms.get("maxRow");
        } else { // 参数为某个实体,该实体拥有Page属性
            Field pageField = ReflectHelper.getFieldByFieldName(parameterObject, "page");
            if (pageField != null) {
                page = (Page) ReflectHelper.getValueByFieldName(parameterObject, "page");
                if (page == null) {
                    return false;
                } else {
                    pageNo = page.getCurrentPageDef();
                    maxRow = page.getShowCount();
                }
            } else {
                throw new NoSuchFieldException(parameterObject.getClass().getName()
                        + "不存在 page 属性!");
            }
        }
        //log.info("page:pageNo=" + pageNo + ",maxRow=" + maxRow);
        super.startPage(pageNo, maxRow);
        return true;
    }

    public void setProperties(Properties p) {
        super.setProperties(p);
        pageSqlId = p.getProperty("pageSqlId");
        if (StringUtils.isEmpty(pageSqlId)) {
            try {
                throw new PropertyException("pageSqlId property is not found!");
            } catch (PropertyException e) {
                e.printStackTrace();
            }
        }
    }
}

 

ReflectHelper

package com.curiousby.util;

import java.lang.reflect.Field;

/**
 * 反射 工具
 * @author baoyou E-mail:curiousby@163.com
 * @version 2017年3月14日 下午4:50:14
 * desc:
 */
public class ReflectHelper {
    /**
     * 获取obj对象fieldName的Field
     * @param obj
     * @param fieldName
     * @return
     */
    public static Field getFieldByFieldName(Object obj, String fieldName) {
        for (Class<?> superClass = obj.getClass(); superClass != Object.class; superClass = superClass
                .getSuperclass()) {
            try {
                return superClass.getDeclaredField(fieldName);
            } catch (NoSuchFieldException e) {
            }
        }
        return null;
    }

    /**
     * 获取obj对象fieldName的属性值
     * @param obj
     * @param fieldName
     * @return
     * @throws SecurityException
     * @throws NoSuchFieldException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     */
    public static Object getValueByFieldName(Object obj, String fieldName)
            throws SecurityException, NoSuchFieldException,
            IllegalArgumentException, IllegalAccessException {
        Field field = getFieldByFieldName(obj, fieldName);
        Object value = null;
        if(field!=null){
            if (field.isAccessible()) {
                value = field.get(obj);
            } else {
                field.setAccessible(true);
                value = field.get(obj);
                field.setAccessible(false);
            }
        }
        return value;
    }

    /**
     * 设置obj对象fieldName的属性值
     * @param obj
     * @param fieldName
     * @param value
     * @throws SecurityException
     * @throws NoSuchFieldException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     */
    public static void setValueByFieldName(Object obj, String fieldName,
            Object value) throws SecurityException, NoSuchFieldException,
            IllegalArgumentException, IllegalAccessException {
        Field field = obj.getClass().getDeclaredField(fieldName);
        if (field.isAccessible()) {
            field.set(obj, value);
        } else {
            field.setAccessible(true);
            field.set(obj, value);
            field.setAccessible(false);
        }
    }
}

 

page

package com.curiousby.util;

import java.io.Serializable;
/**
 * 反射 工具
 * @author baoyou E-mail:curiousby@163.com
 * @version 2017年3月14日 下午4:50:14
 * desc:
 */
public class Page implements Serializable {

    private int showCount = 10; // 每页显示记录数
    private int totalPage; // 总页数
    private int totalResult; // 总记录数
    private int currentPage; // 当前页
    private int currentResult; // 当前记录起始索引
    private boolean entityOrField; // true:需要分页的地方,传入的参数就是Page实体;false:需要分页的地方,传入的参数所代表的实体拥有Page属性
    private String pageStr; // 最终页面显示的底部翻页导航,详细见:getPageStr();

    public Page() {

    }

    public Page(int showCount, int currentPage) {
        this.showCount = showCount;
        this.currentPage = currentPage;
    }

    public int getTotalPage() {
        if (totalResult % showCount == 0) {
            totalPage = totalResult / showCount;
        } else {
            totalPage = totalResult / showCount + 1;
        }
        return totalPage;
    }

    public void setTotalPage(int totalPage) {
        this.totalPage = totalPage;
    }

    public int getTotalResult() {
        return totalResult;
    }

    public void setTotalResult(int totalResult) {
        this.totalResult = totalResult;
    }

    public int getCurrentPage() {
        if (currentPage <= 0) {
            currentPage = 1;
        }
        if (currentPage > getTotalPage()) {
            currentPage = getTotalPage();
        }
        return currentPage;
    }

    public int getCurrentPageDef() {
        return currentPage == 0 ? 1 : currentPage;
    }

    public void setCurrentPage(int currentPage) {
        this.currentPage = currentPage;
    }

    public String getPageStr() {
        StringBuffer sb = new StringBuffer();
        if (totalResult > 0) {
            sb.append("    <ul>\n");
            if (currentPage == 1) {
                sb.append("    <li class=\"pageinfo\">首页</li>\n");
                sb.append("    <li class=\"pageinfo\">上页</li>\n");
            } else {
                sb.append("    <li><a href=\"#@\" onclick=\"nextPage(1)\">首页</a></li>\n");
                sb.append("    <li><a href=\"#@\" onclick=\"nextPage(" + (currentPage - 1)
                        + ")\">上页</a></li>\n");
            }
            int showTag = 3; // 分页标签显示数量
            int startTag = 1;
            if (currentPage > showTag) {
                startTag = currentPage - 1;
            }
            int endTag = startTag + showTag - 1;
            for (int i = startTag; i <= totalPage && i <= endTag; i++) {
                if (currentPage == i) {
                    sb.append("<li class=\"current\">" + i + "</li>\n");
                } else {
                    sb.append("    <li><a href=\"#@\" onclick=\"nextPage(" + i + ")\">" + i
                            + "</a></li>\n");
                }
            }
            if (currentPage == totalPage) {
                sb.append("    <li class=\"pageinfo\">下页</li>\n");
                sb.append("    <li class=\"pageinfo\">尾页</li>\n");
            } else {
                sb.append("    <li><a href=\"#@\" onclick=\"nextPage(" + (currentPage + 1)
                        + ")\">下页</a></li>\n");
                sb.append("    <li><a href=\"#@\" onclick=\"nextPage(" + totalPage
                        + ")\">尾页</a></li>\n");
            }
            sb.append("    <li class=\"pageinfo\">第" + currentPage + "页</li>\n");
            sb.append("    <li class=\"pageinfo\">共" + totalPage + "页</li>\n");
            sb.append("</ul>\n");
            sb.append("<script type=\"text/javascript\">\n");
            sb.append("function nextPage(page){");
            sb.append("    if(true && document.forms[0]){\n");
            sb.append("        var url = document.forms[0].getAttribute(\"action\");\n");
            sb.append("        if(url.indexOf('?')>-1){url += \"&"
                    + (entityOrField ? "currentPage" : "page.currentPage") + "=\";}\n");
            sb.append("        else{url += \"?"
                    + (entityOrField ? "currentPage" : "page.currentPage") + "=\";}\n");
            sb.append("        document.forms[0].action = url+page;\n");
            sb.append("        document.forms[0].submit();\n");
            sb.append("    }else{\n");
            sb.append("        var url = document.location+'';\n");
            sb.append("        if(url.indexOf('?')>-1){\n");
            sb.append("            if(url.indexOf('currentPage')>-1){\n");
            sb.append("                var reg = /currentPage=\\d*/g;\n");
            sb.append("                url = url.replace(reg,'currentPage=');\n");
            sb.append("            }else{\n");
            sb.append("                url += \"&"
                    + (entityOrField ? "currentPage" : "page.currentPage") + "=\";\n");
            sb.append("            }\n");
            sb.append("        }else{url += \"?"
                    + (entityOrField ? "currentPage" : "page.currentPage") + "=\";}\n");
            sb.append("        document.location = url + page;\n");
            sb.append("    }\n");
            sb.append("}\n");
            sb.append("</script>\n");
        }
        pageStr = sb.toString();
        return pageStr;
    }

    public void setPageStr(String pageStr) {
        this.pageStr = pageStr;
    }

    public int getShowCount() {
        return showCount;
    }

    public void setShowCount(int showCount) {
        this.showCount = showCount;
    }

    public int getCurrentResult() {
        currentResult = (getCurrentPage() - 1) * getShowCount();
        if (currentResult < 0) {
            currentResult = 0;
        }
        return currentResult;
    }

    public void setCurrentResult(int currentResult) {
        this.currentResult = currentResult;
    }

    public boolean isEntityOrField() {
        return entityOrField;
    }

    public void setEntityOrField(boolean entityOrField) {
        this.entityOrField = entityOrField;
    }

}

 

package com.curiousby.util;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/** 
 * 分页返回数据
 * @see com.curiousby.RestPage
 * @author baoyou E-mail:curiousby@163.com
 * @version 2017年3月14日 下午4:50:33
 * desc:
 * @param <T>
 */
public class RestPage<T> implements Serializable {

    private static final long serialVersionUID = 5826522161371444844L;
    private List<T> list; // 对象记录结果集
    private int pages = 0; // 总页数
    private int limit = 10; // 每页显示记录数
    private int pageNumber = 1; // 当前页
    private long totalResults = 0; // 总记录数
    private int navigatePages = 5; // 导航页码数
    private boolean isLastPage = false; // 是否为最后一页
    private boolean isFirstPage = false; // 是否为第一页
    private boolean hasNextPage = false; // 是否有下一页
    private boolean hasPreviousPage = false; // 是否有前一页
    private Integer[] navigatePageNumbers; // 所有导航页号

    private HashMap<String, Object> otherHash; //新增结果集

    public RestPage() {
    }

    public RestPage(long total, int pageNumber) {
        init(total, pageNumber, limit);
    }

    public RestPage(long total, int pageNumber, int limit) {
        init(total, pageNumber, limit);
    }

    public RestPage(Page page) {
        if (page != null) {
            init(page.getTotalResult(), page.getCurrentPage(), page.getShowCount());
        } else {
            init(0, 0, 0);
        }
    }

    /**
     * @param params[count,pageNo,maxRow]
     */
    public RestPage(Map<String, Object> params) {
        if (null == params.get("count")) {
            init(0, params.get("pageNo") == null ? 0 : (Integer) params.get("pageNo"),
                    params.get("maxRow") == null ? 0 : (Integer) params.get("maxRow"));
        } else {
            init(Long.parseLong(params.get("count").toString()), (Integer) params.get("pageNo"),
                    (Integer) params.get("maxRow"));
        }
    }

    private void init(long total, int pageNumber, int limit) {
        // 设置基本参数
        this.totalResults = total;
        this.limit = limit;
        if (this.totalResults != 0) {
            this.pages = (int) ((this.totalResults - 1) / this.limit + 1);
        } else {
            this.pages = 0;
        }

        // 根据输入可能错误的当前号码进行自动纠正
        if (pageNumber < 1) {
            this.pageNumber = 1;
        } else if (pageNumber > this.pages) {
            this.pageNumber = this.pages;
        } else {
            this.pageNumber = pageNumber;
        }

        // 基本参数设定之后进行导航页面的计算
        calcNavigatePageNumbers();

        // 以及页面边界的判定
        judgePageBoudary();
    }

    /**
     * 计算导航页
     */
    private void calcNavigatePageNumbers() {
        // 当总页数小于或等于导航页码数时
        if (pages <= navigatePages) {
            navigatePageNumbers = new Integer[pages];
            for (int i = 0; i < pages; i++) {
                navigatePageNumbers[i] = i + 1;
            }
        } else { // 当总页数大于导航页码数时
            navigatePageNumbers = new Integer[navigatePages];
            int startNum = pageNumber - navigatePages / 2;
            int endNum = pageNumber + navigatePages / 2;

            if (startNum < 1) {
                startNum = 1;
                // (最前navigatePages页
                for (int i = 0; i < navigatePages; i++) {
                    navigatePageNumbers[i] = startNum++;
                }
            } else if (endNum > pages) {
                endNum = pages;
                // 最后navigatePages页
                for (int i = navigatePages - 1; i >= 0; i--) {
                    navigatePageNumbers[i] = endNum--;
                }
            } else {
                // 所有中间页
                for (int i = 0; i < navigatePages; i++) {
                    navigatePageNumbers[i] = startNum++;
                }
            }
        }
    }

    /**
     * 判定页面边界
     */
    private void judgePageBoudary() {
        isFirstPage = pageNumber == 1;
        isLastPage = pageNumber == pages && pageNumber != 1;
        hasPreviousPage = pageNumber > 1;
        hasNextPage = pageNumber < pages;
    }

    public void setList(List<T> list) {
        this.list = list;
    }

    /** 
     * 设置结果集返回分页对象
     * @return RestPage<T>
     */
    public RestPage<T> setListAndReturn(List<T> list) {
        this.list = list;
        return this;
    }

    /**
     * 得到当前页的内容
     * @return {List}
     */
    public List<T> getList() {
        return null == list ? new ArrayList<T>() : list;
    }

    public HashMap<String, Object> getOtherHash() {
        return otherHash;
    }

    public RestPage<T> setOtherHash(HashMap<String, Object> otherHash) {
        this.otherHash = otherHash;
        return this;
    }

    /** 
     * 得到记录总数
     * @return long
     */
    public long getTotalResults() {
        return totalResults;
    }

    /**
     * 得到每页显示多少条记录
     * @return {int}
     */
    public int getLimit() {
        return limit;
    }

    /**
     * 得到页面总数
     * 
     * @return {int}
     */
    public int getPages() {
        return pages;
    }

    /**
     * 得到当前页号
     * 
     * @return {int}
     */
    public int getPageNumber() {
        return pageNumber;
    }

    /**
     * 得到所有导航页号
     * 
     * @return {int[]}
     */
    public Integer[] getNavigatePageNumbers() {
        return navigatePageNumbers;
    }

    public boolean isFirstPage() {
        return isFirstPage;
    }

    public boolean isLastPage() {
        return isLastPage;
    }

    /**
     * 
     * @return
     */
    public boolean hasPreviousPage() {
        return hasPreviousPage;
    }

    /**
     * 
     * @return
     */
    public boolean hasNextPage() {
        return hasNextPage;
    }

    /**
     * 
     */
    public String toString() {
        StringBuffer sb = new StringBuffer();
        sb.append("[").append("total=").append(totalResults).append(",pages=").append(pages)
                .append(",pageNumber=").append(pageNumber).append(",limit=").append(limit)
                .append(",isFirstPage=").append(isFirstPage).append(",isLastPage=")
                .append(isLastPage).append(",hasPreviousPage=").append(hasPreviousPage)
                .append(",hasNextPage=").append(hasNextPage).append(",navigatePageNumbers=");
        int len = navigatePageNumbers.length;
        if (len > 0) {
            sb.append(navigatePageNumbers[0]);
        }
        for (int i = 1; i < len; i++) {
            sb.append(" " + navigatePageNumbers[i]);
        }
        sb.append(",list.size=" + list.size());
        sb.append("]");
        return sb.toString();
    }
}

 

pageinfo

public class PageInfo {
    int pageNum = Constants.DEFAUL_PAGE_NUM; // 页号
    int pageSize = Constants.DEFAUL_PAGE_SIZE; // 每页数据条数

    public int getPageNum() {
        return pageNum;
    }

    public void setPageNum(int pageNum) {
        this.pageNum = pageNum;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

}

 

 

mapper

public interface UserMapper {
   
    
    
    RestPage<User> listPage(Map<String, Object> map) ;
    
}

 

controller

 @RequestMapping(value = "/all")
     @ResponseBody
     public  RestPage<User> all(PageInfo page){
        Map<String, Object> filter = new HashMap<String, Object>();
        page.setPageSize(1);
        filter.put("pageNo", page.getPageNum());
        filter.put("maxRow", page.getPageSize());
        RestPage<User> listPage = userService.listPage(filter); 
        
        
        return listPage;
     }

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

捐助开发者

在兴趣的驱动下,写一个免费的东西,有欣喜,也还有汗水,希望你喜欢我的作品,同时也能支持一下。 当然,有钱捧个钱场(右上角的爱心标志,支持支付宝和微信捐助),没钱捧个人场,谢谢各位。



 
 
 谢谢您的赞助,我会做的更好!

 

  

目录
相关文章
|
SQL Java 数据库连接
MyBatis大全
MyBatis大全
52 0
|
3月前
|
SQL Java 数据库连接
Mybatis01
Mybatis01
33 0
|
SQL 算法 Java
Mybatis-plus超详细讲解(2022)
MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。 我们的愿景是成为 MyBatis 最好的搭档,就像 魂斗罗 中的 1P、2P,基友搭配,效率翻倍。
3493 1
|
5月前
|
SQL Java 数据库连接
Mybatis
Mybatis
27 3
|
6月前
|
SQL Java 数据库连接
MyBatis
MyBatis
41 2
|
5月前
|
SQL Java 数据库连接
|
SQL XML Java
【MyBatis】 MyBatis与MyBatis-Plus的区别
【MyBatis】 MyBatis与MyBatis-Plus的区别
4522 0
【MyBatis】 MyBatis与MyBatis-Plus的区别
|
Java 数据库连接 mybatis
MyBatis总结
MyBatis总结
71 0
MyBatis总结
|
Java 数据库连接 C++
MyBatis - MyBatis VS JPA
MyBatis - MyBatis VS JPA
119 0
MyBatis - MyBatis VS JPA