加入收藏 | 设为首页 | 会员中心 | 我要投稿 应用网_阳江站长网 (https://www.0662zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MySql教程 > 正文

Mybatis超详细插件机制解析,弄懂拦截器So easy

发布时间:2019-12-25 20:26:14 所属栏目:MySql教程 来源:站长网
导读:概述 Mybatis插件又称拦截器,本篇文章中出现的拦截器都表示插件。 Mybatis采用责任链模式,通过动态代理组织多个插件(拦截器),通过这些插件可以改变Mybatis的默认行为(诸如SQL重写之类的),由于插件会深入到Mybatis的核心,因此在编写自己的插件前最好了

  private void setPageParameter(String sql, Connection connection, MappedStatement mappedStatement, 

                 BoundSql boundSql, Page page) { 

    // 记录总记录数 

    String countSql = "select count(0) from (" + sql + ") temp"

    PreparedStatement countStmt = null

    ResultSet rs = null

    try { 

      countStmt = connection.prepareStatement(countSql); 

      BoundSql countBS = new BoundSql(mappedStatement.getConfiguration(), countSql, 

          boundSql.getParameterMappings(), boundSql.getParameterObject()); 

      setParameters(countStmt, mappedStatement, countBS, boundSql.getParameterObject()); 

      rs = countStmt.executeQuery(); 

      int totalCount = 0; 

      if (rs.next()) { 

        totalCount = rs.getInt(1); 

      } 

      page.setTotal(totalCount); 

      int totalPage = totalCount / page.getPageSize() + ((totalCount % page.getPageSize() == 0) ? 0 : 1); 

      page.setPages(totalPage); 

    } catch (SQLException e) { 

      log.error("Ignore this exception", e); 

    } finally { 

      try { 

        rs.close(); 

      } catch (SQLException e) { 

        log.error("Ignore this exception", e); 

      } 

      try { 

        countStmt.close(); 

      } catch (SQLException e) { 

        log.error("Ignore this exception", e); 

      } 

    } 

  } 

 

  /** 

   * 代入参数值 

   * 

   * @param ps 

   * @param mappedStatement 

   * @param boundSql 

   * @param parameterObject 

   * @throws SQLException 

   */ 

  private void setParameters(PreparedStatement ps, MappedStatement mappedStatement, BoundSql boundSql, 

                Object parameterObject) throws SQLException { 

    ParameterHandler parameterHandler = new DefaultParameterHandler(mappedStatement, parameterObject, boundSql); 

    parameterHandler.setParameters(ps); 

  } 

 

  @Data //采用lombok插件编译 

  public static class Page<E> { 

    private int pageNum; 

    private int pageSize; 

    private int startRow; 

    private int endRow; 

    private long total; 

    private int pages; 

    private List<E> result; 

 

    public Page(int pageNum, int pageSize) { 

      this.pageNum = pageNum; 

      this.pageSize = pageSize; 

      this.startRow = pageNum > 0 ? (pageNum - 1) * pageSize : 0; 

      this.endRow = pageNum * pageSize; 

    } 

(编辑:应用网_阳江站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!