SpringBoot 分页拦截类 (通过该类实现 分页查询)

2022-06-19 08:35:55

分页连接类,实现页面分页拦截 分页方法必须要以(querypage)开头,这个自定义。mapper接口需要传入一个名为page的对象

/**
 * 实现mybatis分页功能拦截器
 * @author ZH_FTP
 *
 */
@Component
@Intercepts({@Signature(type= StatementHandler.class, method="prepare", args={Connection.class,Integer.class}), @Signature(type= ResultSetHandler.class, method="handleResultSets", args={Statement.class})})publicclassPageHelperInterceptsimplementsInterceptor{privatestatic final StringSELECT_ID="querypage";//设置方法以这个开头的实现分页 注 不需要分页的避免名称开头/**
	 * 分页拦截器
	 */
	@Overridepublic Objectintercept(Invocation invocation) throws Throwable{if(invocation.getTarget()instanceofStatementHandler){/**获取JDBC Statement操作(被代理对象)*/
			StatementHandler statementHandler=(StatementHandler) invocation.getTarget();
			MetaObject metaStatementHandler= SystemMetaObject.forObject(statementHandler);/**获取xml配置的中操作节点*/
			MappedStatement mappedStatement=(MappedStatement) metaStatementHandler.getValue("delegate.mappedStatement");/**获取节点ID*/
			String selectId= mappedStatement.getId();
			String lowerCase= selectId.substring(selectId.lastIndexOf(".")+1).toLowerCase();/**当节点ID名称以SELECT_ID起始时 拦截*/if(lowerCase!=null&& lowerCase.startsWith(SELECT_ID)){/**获取动态生成的SQL语句以及相应的参数信息*/
				BoundSql boundSql=(BoundSql) metaStatementHandler.getValue("delegate.boundSql");// 分页参数作为参数对象parameterObject的一个属性
				String sql= boundSql.getSql();
				Object parameterObject= boundSql.getParameterObject();if(parameterObject==null){thrownewNullPointerException("parameterObject is null!");}
				Object obj= metaStatementHandler.getValue("delegate.boundSql.parameterObject.page");// 传入了page参数且需要开启分页时if(obj!=null&& objinstanceofPageBean){
					PageBean pageBean=(PageBean) obj;// 重写sql
					String countSql=assembleCountSql(sql);
					String pageSql=assemblePageSql(sql, pageBean);
					Connection connection=(Connection) invocation.getArgs()[0];/**统计数据行数*/
					int totalCount=ProcessingPagingStatisticsResults(countSql, connection, mappedStatement, boundSql);/**绑定分页sql语句*/
					metaStatementHandler.setValue("delegate.boundSql.sql", pageSql);/**绑定count*/
					pageBean.setTotalCount(totalCount);}}}return invocation.proceed();}/**
	 * 统计数据行数分析
	 * @param countSql
	 * @param connection
	 * @param mappedStatement
	 * @param boundSql
	 * @return
	 */private IntegerProcessingPagingStatisticsResults(String countSql,Connection connection,MappedStatement mappedStatement,BoundSql boundSql){
		PreparedStatement countStmt=null;
		ResultSet resultSet=null;
		int totalCount=0;try{
			countStmt= connection.prepareStatement(countSql);/**生成动态统计行数的sql语句以及参数*/
			BoundSql countBS=newBoundSql(mappedStatement.getConfiguration(), countSql,boundSql.getParameterMappings(), boundSql.getParameterObject());setParameters(countStmt, mappedStatement, countBS, boundSql.getParameterObject());/**提交查询行数*/
			resultSet= countStmt.executeQuery();if(resultSet.next()){
				totalCount= resultSet.getInt(1);}}catch(SQLException e){
			System.out.println("Ignore this exception"+ e);}finally{try{if(resultSet!=null)resultSet.close();if(countStmt!=null)countStmt.close();}catch(SQLException e){
				System.out.println("Ignore this exception"+ e);}}return totalCount;}
	
    @Overridepublic Objectplugin(Object target){if(targetinstanceofStatementHandler){return Plugin.wrap(target,this);}else{return target;}}
    @OverridepublicvoidsetProperties(Properties properties){}/**
     * 对SQL参数(?)设值
     * 
     * @param ps 参数
     * @param mappedStatement 参数
     * @param boundSql 绑定sql
     * @param parameterObject 参数对象
     * @throws SQLException 抛出sql异常
     */privatevoidsetParameters(PreparedStatement ps, MappedStatement mappedStatement, BoundSql boundSql,Object parameterObject) throws SQLException{
        ParameterHandler parameterHandler=newDefaultParameterHandler(mappedStatement, parameterObject, boundSql);
        parameterHandler.setParameters(ps);}/**
     * 组装统计sql语句
     * @param sql
     * @return
     */public StringassembleCountSql(String sql){
        StringBuffer sb=newStringBuffer("select count(*) from ");/**tempsql sql语句转换为小写 */
        String tempsql= sql.toLowerCase();if(tempsql.lastIndexOf("order")>tempsql.lastIndexOf(")")){
            sb.append(sql.substring(tempsql.indexOf("from")+4, tempsql.lastIndexOf("order")));}else{
            sb.append(sql.substring(tempsql.indexOf("from")+4));}return sb.toString();}/**
     * 实现分页sql生成
     * @param sql
     * @param co
     * @return
     */public StringassemblePageSql(String sql,PageBean co){
        StringBuffer sb=newStringBuffer();
        sb.append(sql);
        sb.append(" limit ").append(co.calculationStartLine()).append(" , ").append(co.getPageSize());return sb.toString();}

page对象实体类

/**
 * 分页公共类
 * @author ZH_FTP
 *
 * @param <T>
 */publicclassPageBeanimplementsSerializable{privatestatic final int defaultPageNum=1;privatestatic final int defaultPageSize=10;privatestatic final long serialVersionUID=1L;publicPageBean(){super();this.pageNum= defaultPageNum;this.pageSize= defaultPageSize;}publicPageBean(String sPageNum,String sPageSize){super();/** 数据类型转换 并检查页码,显示数量是否合法,不合法赋默认值 */
		int pageNum= Integer.parseInt(sPageNum);
		int pageSize= Integer.parseInt(sPageSize);if(pageNum< defaultPageNum){
			pageNum= defaultPageNum;}if(pageSize< defaultPageNum){
			pageSize= defaultPageSize;}this.pageNum= pageNum;this.pageSize= pageSize;}private Integer pageNum;private Integer pageSize;private Integer totalCount;private Integer totalPage;private List<?> rows;public IntegergetPageNum(){return pageNum;}publicvoidsetPageNum(Integer pageNum){this.pageNum= pageNum;}public IntegergetPageSize(){return pageSize;}publicvoidsetPageSize(Integer pageSize){this.pageSize= pageSize;}public IntegergetTotalCount(){return totalCount;}publicvoidsetTotalCount(Integer totalCount){this.totalCount= totalCount;/** 计算总页数 */this.totalPage=(totalCount+ pageSize-1)/ pageSize;}public IntegergetTotalPage(){return totalPage;}publicvoidsetTotalPage(Integer totalPage){this.totalPage= totalPage;}public List<?>getRows(){return rows;}publicvoidsetRows(List<?> rows){/** 数组为空时 赋值空数组 */if(rows==null){
			rows=newArrayList<Object>();}this.rows= rows;}public IntegercalculationStartLine(){/** 计算起始值 */return((pageNum-1)* pageSize);}}
  • 作者:Yweir
  • 原文链接:https://laiwei.blog.csdn.net/article/details/108422864
    更新时间:2022-06-19 08:35:55