搜索
首页Javajava教程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>

更多Java简单实现SpringMVC+MyBatis分页插件相关文章请关注PHP中文网!


声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
是否有任何威胁或增强Java平台独立性的新兴技术?是否有任何威胁或增强Java平台独立性的新兴技术?Apr 24, 2025 am 12:11 AM

新兴技术对Java的平台独立性既有威胁也有增强。1)云计算和容器化技术如Docker增强了Java的平台独立性,但需要优化以适应不同云环境。2)WebAssembly通过GraalVM编译Java代码,扩展了其平台独立性,但需与其他语言竞争性能。

JVM的实现是什么,它们都提供了相同的平台独立性?JVM的实现是什么,它们都提供了相同的平台独立性?Apr 24, 2025 am 12:10 AM

不同JVM实现都能提供平台独立性,但表现略有不同。1.OracleHotSpot和OpenJDKJVM在平台独立性上表现相似,但OpenJDK可能需额外配置。2.IBMJ9JVM在特定操作系统上表现优化。3.GraalVM支持多语言,需额外配置。4.AzulZingJVM需特定平台调整。

平台独立性如何降低发展成本和时间?平台独立性如何降低发展成本和时间?Apr 24, 2025 am 12:08 AM

平台独立性通过在多种操作系统上运行同一套代码,降低开发成本和缩短开发时间。具体表现为:1.减少开发时间,只需维护一套代码;2.降低维护成本,统一测试流程;3.快速迭代和团队协作,简化部署过程。

Java的平台独立性如何促进代码重用?Java的平台独立性如何促进代码重用?Apr 24, 2025 am 12:05 AM

Java'splatformindependencefacilitatescodereusebyallowingbytecodetorunonanyplatformwithaJVM.1)Developerscanwritecodeonceforconsistentbehavioracrossplatforms.2)Maintenanceisreducedascodedoesn'tneedrewriting.3)Librariesandframeworkscanbesharedacrossproj

您如何在Java应用程序中对平台特定问题进行故障排除?您如何在Java应用程序中对平台特定问题进行故障排除?Apr 24, 2025 am 12:04 AM

要解决Java应用程序中的平台特定问题,可以采取以下步骤:1.使用Java的System类查看系统属性以了解运行环境。2.利用File类或java.nio.file包处理文件路径。3.根据操作系统条件加载本地库。4.使用VisualVM或JProfiler优化跨平台性能。5.通过Docker容器化确保测试环境与生产环境一致。6.利用GitHubActions在多个平台上进行自动化测试。这些方法有助于有效地解决Java应用程序中的平台特定问题。

JVM中的类加载程序子系统如何促进平台独立性?JVM中的类加载程序子系统如何促进平台独立性?Apr 23, 2025 am 12:14 AM

类加载器通过统一的类文件格式、动态加载、双亲委派模型和平台无关的字节码,确保Java程序在不同平台上的一致性和兼容性,实现平台独立性。

Java编译器会产生特定于平台的代码吗?解释。Java编译器会产生特定于平台的代码吗?解释。Apr 23, 2025 am 12:09 AM

Java编译器生成的代码是平台无关的,但最终执行的代码是平台特定的。1.Java源代码编译成平台无关的字节码。2.JVM将字节码转换为特定平台的机器码,确保跨平台运行但性能可能不同。

JVM如何处理不同操作系统的多线程?JVM如何处理不同操作系统的多线程?Apr 23, 2025 am 12:07 AM

多线程在现代编程中重要,因为它能提高程序的响应性和资源利用率,并处理复杂的并发任务。JVM通过线程映射、调度机制和同步锁机制,在不同操作系统上确保多线程的一致性和高效性。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

螳螂BT

螳螂BT

Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

功能强大的PHP集成开发环境

安全考试浏览器

安全考试浏览器

Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)