mybatis 拦截器分页

public class Pager {  // 一 这是一个分页工具类(没有写全)

    private List resultList;   //用于封装返回的结果
    private int currentPage = 1;  //默认第一页
    private int pages;

    private int pageSize = 20;   // 页面大小默认为20  最后实际大小根据页面来定
    private Long totalSize;      // 总记录条数
    private Long operate;        // 操作标志

    private int sortField ;
    private int sortMethod;

    public Pager() {
    }

    public Pager(int currentPage, int pageSize) {
        this.currentPage = currentPage;
        this.pageSize = pageSize;
    }


    public Pager(List resultList, int currentPage, int pages, int pageSize, int totalSize) {
        this.resultList = resultList;
        this.currentPage = currentPage;
        this.pages = pages;
        this.pageSize = pageSize;
        this.totalSize = (long)totalSize;
    }

    public List getResultList() {
        return resultList;
    }

    public void setResultList(List resultList) {
        this.resultList = resultList;
    }

    public int getCurrentPage() {
        return currentPage;
    }

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

    public int getPages() {
        return pages;
    }

    public void setPages(int pages) {
        this.pages = pages;
    }

    public int getPageSize() {
        return pageSize;
    }

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

    public Long getTotalSize() {
        return totalSize;
    }

    public void setTotalSize(Long totalSize) {
        this.totalSize = totalSize;
    }

    public Long getOperate() {
        return operate;
    }

    public void setOperate(Long operate) {
        this.operate = operate;
    }

    public int getSortField() {
        return sortField;
    }

    public void setSortField(int sortField) {
        this.sortField = sortField;
    }

    public int getSortMethod() {
        return sortMethod;
    }

    public void setSortMethod(int sortMethod) {
        this.sortMethod = sortMethod;
    }
}
二  反射工具类
public class ReflectUtil {
    // 因为安装了较高版本的jdk The type java.lang.reflect.AnnotatedElement cannot be resolved. It is indirectly referenced from required .class files
    private static Field getField(Object obj , String fm){
        Field f = null;
        for(Class<?> clazz = obj.getClass() ; clazz != Object.class;clazz = clazz.getSuperclass()){
            try {
                f = clazz.getDeclaredField(fm);
            } catch (NoSuchFieldException  e) {
                // TODO: handle exception
                System.out.println("NoSuchFieldException-------111111111111111  e");
               /* e.printStackTrace();*/

            }catch (SecurityException e) {
                // TODO: handle exception
               /* e.printStackTrace();*/
                System.out.println("SecurityException--------11111111111-2222222222  e");
            }
        }
        return f ;
    }

    public static Object getFieldValue(Object obj, String fm) {
        Object result = null;
        Field f = ReflectUtil.getField(obj, fm);
        if (f != null) {
            f.setAccessible(true);
            try {
                result = f.get(obj);
            } catch (IllegalArgumentException e) {
                // TODO: handle exception
             /*   e.printStackTrace();*/
                System.out.println("22222  IllegalArgumentException e ");
            } catch (IllegalAccessException e) {
                // TODO: handle exception
               /* e.printStackTrace();*/
                System.out.println("22222---2222  IllegalAccessException e ");
            }
        }
        return result;
    }

    public static void setFieldValue (Object obj , String fieldName , Object  fieldValue){
        Field f = ReflectUtil.getField(obj, fieldName);
        if(f!=null){
            f.setAccessible(true);
            try{
                f.set(obj, fieldValue);
            }catch (IllegalArgumentException e) {
                // TODO: handle exception
               /* e.printStackTrace();*/
                System.out.println("333333333333   IllegalArgumentException e ");
            }catch (IllegalAccessException e) {
                // TODO: handle exception
              /*  e.printStackTrace();*/
                System.out.println("333333333333--33333   IllegalAccessException e ");
            }
        }
    }


}

三 拦截器分页
@Intercepts({
      /*
       * @Signature(method="prepare" , type = StatementHandler.class ,
       * args={Connection.class , Integer.class })
       */
        @Signature(args = { Connection.class,
                Integer.class }, method = "prepare", type = StatementHandler.class) })
public class PageInterceptor implements Interceptor {
    private String databaseType;
    // 1.
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        RoutingStatementHandler handle = (RoutingStatementHandler) invocation.getTarget();
        StatementHandler delegate = (StatementHandler) ReflectUtil.getFieldValue(handle, "delegate");
        BoundSql boundSql = delegate.getBoundSql();
        Object obj = boundSql.getParameterObject();
     /*   Object obj2 = ReflectUtil.getFieldValue(boundSql, "additionalparameters");*/
        if (obj != null && obj instanceof Map) {
            Map condition = (Map) obj;
            if (condition.containsKey("page")) {

            }
            Pager page = (Pager) condition.get("page");
            MappedStatement mappedStatement = (MappedStatement) ReflectUtil.getFieldValue(delegate, "mappedStatement");

            String sql = boundSql.getSql();
            String pageSql = "oracle".equalsIgnoreCase(databaseType)
                    ? this.getOraclePageSql(page, new StringBuffer(sql))
                    : "mysql".equalsIgnoreCase(databaseType) ? this.getStPageSql(page, new StringBuffer(sql))
                    : this.getMyPageSql(page, new StringBuffer(sql));

            ReflectUtil.setFieldValue(boundSql, "sql", pageSql);

        }

        Object o = invocation.proceed();
        return o;
    }

    private String getMyPageSql(Pager page, StringBuffer sb) {
        int offset = (page.getCurrentPage() - 1) * page.getPageSize();
        sb.append(" limit ").append(offset).append(" , ").append(page.getPageSize() + 1);
        return sb.toString();
    }

    private String getOraclePageSql(Pager page, StringBuffer sb) {
        int offset = (page.getCurrentPage() - 1) * page.getPageSize();
        sb.insert(0, "select u.*, rownum r from (").append(") u where rownum< ").append(offset + page.getPageSize());

        sb.insert(0, "select * from ( ").append(" ) where >= ").append(offset);
        return sb.toString();

    }

    private String getStPageSql(Pager page, StringBuffer sb) {
        int offset = (page.getCurrentPage() - 1) * page.getPageSize();
       /* StringBuffer sb2 = new StringBuffer(
                sb.toString().replaceAll("order\\s+by.+\\)", ")").replaceAll("order\\s+by.+$", "")
                        .replaceAll("ORDER\\s+BY.+\\)", ")").replaceAll("ORDER\\s+BY.+$", ""));

        sb = sb2;
        sb2.append(" order by ").append(page.getSortField());
        if (page.getSortMethod() == 1) {
            sb2.append(" desc ");
        }*/
        sb.append(" limit ").append(page.getPageSize() + 1).append(" offset ").append(offset);
        return sb.toString();
    }


    // 2.
    @Override
    public Object plugin(Object target) {
        if (target instanceof RoutingStatementHandler){
            return Plugin.wrap(target,this);
        }
        return target;
    }
    // 3.
    @Override
    public void setProperties(Properties properties) {
        this.databaseType = properties.getProperty("databaseType");
    }
}

四  配置 mybatis-config
 
<!--配置分页拦截器使用 
interceptor  全限定类名
--><plugins> <plugin interceptor="com.spring.common.interceptor.PageInterceptor"> <property name="databaseType" value="mysql"></property> </plugin></plugins>
五 配置sping 的分页
<!--配置mybatis配置文件-->    <!--里面有分頁信息-->
<property name="configLocation" value="classpath:/mybatise/mybatise-config.xml"></property>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值