Java简单实现SpringMVC+MyBatis分页插件

1.封装分页Page类

package com.framework.common.page.impl;

import java.io.Serializable;

import com.framework.common.page.IPage;
/**
 *
 *
 *
 */
public abstract class BasePage implements IPage, Serializable {

  /**
   *
   */
  private static final long serialVersionUID = -3623448612757790359L;

  public static int DEFAULT_PAGE_SIZE = 20;
  private int pageSize = DEFAULT_PAGE_SIZE;
  private int currentResult;
  private int totalPage;
  private int currentPage = 1;
  private int totalCount = -1;

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

  public int getTotalCount() {
    return this.totalCount;
  }

  public void setTotalCount(int totalCount) {
    if (totalCount < 0) {
      this.totalCount = 0;
      return;
    }
    this.totalCount = totalCount;
  }

  public BasePage() {
  }

  public int getFirstResult() {
    return (this.currentPage - 1) * this.pageSize;
  }

  public void setPageSize(int pageSize) {
    if (pageSize < 0) {
      this.pageSize = DEFAULT_PAGE_SIZE;
      return;
    }
    this.pageSize = pageSize;
  }

  public int getTotalPage() {
    if (this.totalPage <= 0) {
      this.totalPage = (this.totalCount / this.pageSize);
      if ((this.totalPage == 0) || (this.totalCount % this.pageSize != 0)) {
        this.totalPage += 1;
      }
    }
    return this.totalPage;
  }

  public int getPageSize() {
    return this.pageSize;
  }

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

  public int getPageNo() {
    return this.currentPage;
  }

  public boolean isFirstPage() {
    return this.currentPage <= 1;
  }

  public boolean isLastPage() {
    return this.currentPage >= getTotalPage();
  }

  public int getNextPage() {
    if (isLastPage()) {
      return this.currentPage;
    }
    return this.currentPage + 1;
  }

  public int getCurrentResult() {
    this.currentResult = ((getPageNo() - 1) * getPageSize());
    if (this.currentResult < 0) {
      this.currentResult = 0;
    }
    return this.currentResult;
  }

  public int getPrePage() {
    if (isFirstPage()) {
      return this.currentPage;
    }
    return this.currentPage - 1;
  }

}
package com.framework.common.page.impl;

import java.util.List;
/**
 *
 *
 *
 */
public class Page extends BasePage {

  /**
   *
   */
  private static final long serialVersionUID = -970177928709377315L;

  public static ThreadLocal<Page> threadLocal = new ThreadLocal<Page>();

  private List<?> data; 

  public Page() {
  }

  public Page(int currentPage, int pageSize, int totalCount) {
    super(currentPage, pageSize, totalCount);
  }

  public Page(int currentPage, int pageSize, int totalCount, List<?> data) {
    super(currentPage, pageSize, totalCount);
    this.data = data;
  }

  public List<?> getData() {
    return data;
  }

  public void setData(List<?> data) {
    this.data = data;
  }

}

2.封装分页插件

package com.framework.common.page.plugin;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Properties;

import javax.xml.bind.PropertyException;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.executor.ErrorContext;
import org.apache.ibatis.executor.ExecutorException;
import org.apache.ibatis.executor.statement.BaseStatementHandler;
import org.apache.ibatis.executor.statement.RoutingStatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.ParameterMode;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.property.PropertyTokenizer;
import org.apache.ibatis.scripting.xmltags.ForEachSqlNode;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.type.TypeHandler;
import org.apache.ibatis.type.TypeHandlerRegistry;

import com.framework.common.page.impl.Page;
import com.framework.common.utils.ReflectUtil;
/**
 *
 *
 *
 */
@Intercepts({ @org.apache.ibatis.plugin.Signature(type = org.apache.ibatis.executor.statement.StatementHandler.class, method = "prepare", args = { Connection.class }) })
public class PagePlugin implements Interceptor {

  private String dialect = "";
  private String pageSqlId = "";

  @Override
  public Object intercept(Invocation invocation) throws Throwable {
    if (invocation.getTarget() instanceof RoutingStatementHandler) {
      BaseStatementHandler delegate = (BaseStatementHandler) ReflectUtil
          .getValueByFieldName(
              (RoutingStatementHandler) invocation.getTarget(),
              "delegate");
      MappedStatement mappedStatement = (MappedStatement) ReflectUtil
          .getValueByFieldName(delegate,
              "mappedStatement");

      Page page = Page.threadLocal.get();
      if (page == null) {
        page = new Page();
        Page.threadLocal.set(page);
      }

      if (mappedStatement.getId().matches(".*(" + this.pageSqlId + ")$") && page.getPageSize() > 0) {
        BoundSql boundSql = delegate.getBoundSql();
        Object parameterObject = boundSql.getParameterObject();

        String sql = boundSql.getSql();
        String countSqlId = mappedStatement.getId().replaceAll(pageSqlId, "Count");
        MappedStatement countMappedStatement = null;
        if (mappedStatement.getConfiguration().hasStatement(countSqlId)) {
          countMappedStatement = mappedStatement.getConfiguration().getMappedStatement(countSqlId);
        }
        String countSql = null;
        if (countMappedStatement != null) {
          countSql = countMappedStatement.getBoundSql(parameterObject).getSql();
        } else {
          countSql = "SELECT COUNT(1) FROM (" + sql + ") T_COUNT";
        }

        int totalCount = 0;
        PreparedStatement countStmt = null;
        ResultSet resultSet = null;
        try {
          Connection connection = (Connection) invocation.getArgs()[0];
          countStmt = connection.prepareStatement(countSql);
          BoundSql countBoundSql = new BoundSql(mappedStatement.getConfiguration(), countSql, boundSql.getParameterMappings(), parameterObject);

          setParameters(countStmt, mappedStatement, countBoundSql, parameterObject);

          resultSet = countStmt.executeQuery();
          if(resultSet.next()) {
            totalCount = resultSet.getInt(1);
          }
        } catch (Exception e) {
          throw e;
        } finally {
          try {
            if (resultSet != null) {
              resultSet.close();
            }
          } finally {
            if (countStmt != null) {
              countStmt.close();
            }
          }
        }

        page.setTotalCount(totalCount);

        ReflectUtil.setValueByFieldName(boundSql, "sql", generatePageSql(sql,page));
      }
    }

    return invocation.proceed();
  }

  /**
   * 对SQL参数(?)设值,参考org.apache.ibatis.executor.parameter.DefaultParameterHandler
   * @param ps
   * @param mappedStatement
   * @param boundSql
   * @param parameterObject
   * @throws SQLException
   */
  private void setParameters(PreparedStatement ps,MappedStatement mappedStatement,BoundSql boundSql,Object parameterObject) throws SQLException {
    ErrorContext.instance().activity("setting parameters").object(mappedStatement.getParameterMap().getId());
    List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
    if (parameterMappings != null) {
      Configuration configuration = mappedStatement.getConfiguration();
      TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
      MetaObject metaObject = parameterObject == null ? null: configuration.newMetaObject(parameterObject);
      for (int i = 0; i < parameterMappings.size(); i++) {
        ParameterMapping parameterMapping = parameterMappings.get(i);
        if (parameterMapping.getMode() != ParameterMode.OUT) {
          Object value;
          String propertyName = parameterMapping.getProperty();
          PropertyTokenizer prop = new PropertyTokenizer(propertyName);
          if (parameterObject == null) {
            value = null;
          } else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
            value = parameterObject;
          } else if (boundSql.hasAdditionalParameter(propertyName)) {
            value = boundSql.getAdditionalParameter(propertyName);
          } else if (propertyName.startsWith(ForEachSqlNode.ITEM_PREFIX)&& boundSql.hasAdditionalParameter(prop.getName())) {
            value = boundSql.getAdditionalParameter(prop.getName());
            if (value != null) {
              value = configuration.newMetaObject(value).getValue(propertyName.substring(prop.getName().length()));
            }
          } else {
            value = metaObject == null ? null : metaObject.getValue(propertyName);
          }
          TypeHandler typeHandler = parameterMapping.getTypeHandler();
          if (typeHandler == null) {
            throw new ExecutorException("There was no TypeHandler found for parameter "+ propertyName + " of statement "+ mappedStatement.getId());
          }
          typeHandler.setParameter(ps, i + 1, value, parameterMapping.getJdbcType());
        }
      }
    }
  } 

  /**
   * 根据数据库方言,生成特定的分页sql
   * @param sql
   * @param page
   * @return
   */
  private String generatePageSql(String sql,Page page){
    if(page!=null && StringUtils.isNotBlank(dialect)){
      StringBuffer pageSql = new StringBuffer();
      if("mysql".equals(dialect)){
        pageSql.append(sql);
        pageSql.append(" LIMIT "+page.getCurrentResult()+","+page.getPageSize());
      }else if("oracle".equals(dialect)){
        pageSql.append("SELECT * FROM (SELECT TMP_TB.*,ROWNUM ROW_ID FROM (");
        pageSql.append(sql);
        pageSql.append(") AS TMP_TB WHERE ROWNUM <= ");
        pageSql.append(page.getCurrentResult()+page.getPageSize());
        pageSql.append(") WHERE ROW_ID > ");
        pageSql.append(page.getCurrentResult());
      }
      return pageSql.toString();
    }else{
      return sql;
    }
  } 

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

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

}

3.MyBatis配置文件:mybatis-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD SQL Map Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
  <plugins>
    <plugin interceptor="com.framework.common.page.plugin.PagePlugin">
      <property name="dialect" value="mysql" />
      <property name="pageSqlId" value="ByPage" />
    </plugin>
  </plugins>
</configuration>

4.分页拦截器

package com.framework.common.page.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.framework.common.page.impl.Page;
/**
*
* 14 *
*/
public class PageInterceptor extends HandlerInterceptorAdapter {

 @Override
 public void postHandle(HttpServletRequest request,
     HttpServletResponse response, Object handler,
     ModelAndView modelAndView) throws Exception {
   super.postHandle(request, response, handler, modelAndView);
   Page page = Page.threadLocal.get();
   if (page != null) {
     request.setAttribute("page", page);
   }
   Page.threadLocal.remove();
 }

 @Override
 public boolean preHandle(HttpServletRequest request,
     HttpServletResponse response, Object handler) throws Exception {
   String pageSize = request.getParameter("pageSize");
   String pageNo = request.getParameter("pageNo");
   Page page = new Page();
   if (NumberUtils.isNumber(pageSize)) {
     page.setPageSize(NumberUtils.toInt(pageSize));
   }
   if (NumberUtils.isNumber(pageNo)) {
     page.setPageNo(NumberUtils.toInt(pageNo));
   }
   Page.threadLocal.set(page);
   return true;
 }

}

5.Spring配置

<!-- ===================================================================
- Load property file
- =================================================================== -->
<context:property-placeholder location="classpath:application.properties" />

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  <property name="dataSource" ref="dataSource" />
  <property name="configLocation" value="classpath:mybatis-config.xml" />
  <property name="mapperLocations">
    <list>
      <value>classpath:/com/framework/mapper/**/*Mapper.xml</value>
    </list>
  </property>
</bean>

<!-- ===================================================================
- 通过扫描的模式,扫描目录下所有的dao, 根据对应的mapper.xml为其生成代理类
- =================================================================== -->
<bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
  <property name="basePackage" value="com.framework.dao" />
  <property name="processPropertyPlaceHolders" value="true" />
  <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>

6.SpringMVC配置拦截器

<!-- 分页拦截器 -->
  <bean id="pageInterceptor" class="com.framework.common.page.interceptor.PageInterceptor"></bean>

  <!-- 配置拦截器 -->
  <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">
    <property name="interceptors">
      <list>
        <ref bean="pageInterceptor" />
      </list>
    </property>
  </bean>
(0)

相关推荐

  • springmvc 分页查询的简单实现示例代码

    目前较常用的分页实现办法有两种: 1.每次翻页都修改SQL,向SQL传入相关参数去数据库实时查出该页的数据并显示. 2.查出数据库某张表的全部数据,再通过在业务逻辑里面进行处理去取得某些数据并显示. 对于数据量并不大的简单的管理系统而言,第一种实现方法相对来说容易使用较少的代码实现分页这一功能,本文也正是为大家介绍这种方法: 代码片段: 1,Page.java package com.cm.contract.common; import org.apache.commons.lang.Strin

  • Spring MVC结合Spring Data JPA实现按条件查询和分页

    本文实例为大家分享了Android九宫格图片展示的具体代码,供大家参考,具体内容如下 推荐视频:尚硅谷Spring Data JPA视频教程,一学就会,百度一下就有. 后台代码:在DAO层继承Spring Data JPA的PagingAndSortingRepository接口实现的 (实现方法主要在SbglServiceImpl.java类中) 前台表现:用kkpaper表现出来 实现效果: 1.实体类 package com.jinhetech.yogurt.sbgl.entity; im

  • springboot用thymeleaf模板的paginate分页完整代码

    本文根据一个简单的user表为例,展示 springboot集成mybatis,再到前端分页完整代码(新手自学,不足之处欢迎纠正): 先看java部分 pom.xml 加入 <!--支持 Web 应用开发,包含 Tomcat 和 spring-mvc. --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web&l

  • SpringMvc+Mybatis+Pagehelper分页详解

    最近公司需要做一个告警页面的功能,需要分页,查了很多资料发现PageHelper比较合适 故写一篇从零开始的PageHelper使用的教程,也记录下忙活一天的东西 1.首先需要在项目中添加PageHelper的依赖,这里我用的Maven添加 <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>

  • struts2+spring+hibernate分页代码[比较多]第1/7页

    dao层接口: Java代码 复制代码 代码如下: package com.last999.im.news.dao; import java.util.*; import com.last999.im.news.entity.KindEntity; import com.last999.im.news.web.PageTool; public interface KindEntityDao{ public KindEntity get(String uuid); public void save

  • Spring Data JPA实现分页Pageable的实例代码

    在JPA中提供了很方便的分页功能,那就是Pageable(org.springframework.data.domain.Pageable)以及它的实现类PageRequest(org.springframework.data.domain.PageRequest),详细的可以见示例代码. 1.改变CustomerRepository方法​ /** * 一个参数,匹配两个字段 * @param name2 * @Param pageable 分页参数 * @return * 这里Param的值和

  • spring data jpa分页查询示例代码

    最近项目上用就hibernate+spring data jpa,一开始感觉还不错,但是随着对业务的复杂,要求处理一些复杂的sql,就顺便研究了下,把结果记录下,以便日后查看.用到Specification,需要继承JpaSpecificationExecutor接口.(下面代码有的分页从0开始作为第一页,有的从1开始作为作为第一页,我也忘记,请自己测试) DAO层: import java.util.List; import org.springframework.data.domain.Pa

  • SpringBoot JPA实现增删改查、分页、排序、事务操作等功能示例

    今天给大家介绍一下SpringBoot中JPA的一些常用操作,例如:增删改查.分页.排序.事务操作等功能. 下面先来介绍一下JPA中一些常用的查询操作: //And --- 等价于 SQL 中的 and 关键字,比如 findByHeightAndSex(int height,char sex): public List<User> findByHeightAndSex(int height,char sex); // Or --- 等价于 SQL 中的 or 关键字,比如 findByHei

  • Spring Data JPA 复杂/多条件组合分页查询

    话不多说,请看代码: public Map<String, Object> getWeeklyBySearch(final Map<String, String> serArgs, String pageNum, String pageSize) throws Exception { // TODO Auto-generated method stub Map<String,Object> resultMap=new HashMap<String, Object&

  • 基于SpringMVC+Bootstrap+DataTables实现表格服务端分页、模糊查询

    前言 基于SpringMVC+Bootstrap+DataTables实现数据表格服务端分页.模糊查询(非DataTables Search),页面异步刷新. 说明:sp:message标签是使用了SpringMVC国际化 效果 DataTable表格 关键字查询 自定义关键字查询,非DataTable Search 代码 HTML代码 查询条件代码 <!-- 查询.添加.批量删除.导出.刷新 --> <div class="row-fluid"> <di

随机推荐