@SuppressWarnings({"rawtypes", "unchecked"})
  private void autoMap(Invocation invocation, String name) throws ClassNotFoundException {
    final Object[] queryArgs = invocation.getArgs();
    final MappedStatement ms = (MappedStatement) queryArgs[0];
    final Object parameter = queryArgs[1];
    String statementId = ms.getId();
    MapperMeta meta = getMapperMeta(ms.getConfiguration(), statementId);
    if (meta.isFillEntity()) {
      // 将泛型类加入到参数中供CrudTemplate使用
      if (parameter != null) {
        Map map;
        if (parameter instanceof Map) {
          map = (HashMap) parameter;
          map.put(CrudProvider.CLASS_KEY, meta.getEntity());
        } else {
          map = new HashMap();
          map.put(CrudProvider.PARA_KEY, parameter);
          map.put(CrudProvider.CLASS_KEY, meta.getEntity());
        }
        queryArgs[1] = map;
      } else {
        queryArgs[1] = meta.getEntity();
      }
    }

    if (meta.isFillResultMap()) {
      MetaObject metaMappedStatement = getMetaObject(ms);
      metaMappedStatement.setValue("resultMaps", meta.getResultMaps());
    }

    if (name.equals("query")) {
      final RowBounds rowBounds = (RowBounds) queryArgs[2];
      if (rowBounds == null || rowBounds == RowBounds.DEFAULT) {
        Page p = findPageParameter(queryArgs[1]);
        if (p != null) {
          queryArgs[2] = new RowBounds(p.getOffset(), p.getLimit());
        }
      }
    }
  }
  /**
   * 获取总记录数
   *
   * @param sql 原始sql语句
   * @param conn
   * @param ms
   * @param boundSql
   * @return
   * @throws SQLException
   */
  private int getTotalCount(String sql, Connection conn, MappedStatement ms, BoundSql boundSql)
      throws SQLException {
    int start = sql.indexOf("from");
    if (start == -1) {
      throw new RuntimeException("statement has no 'from' keyword");
    }
    int stop = sql.indexOf("order by");
    if (stop == -1) {
      stop = sql.length();
    }

    String countSql = "select count(0) " + sql.substring(start, stop);
    BoundSql countBoundSql =
        new BoundSql(
            ms.getConfiguration(),
            countSql,
            boundSql.getParameterMappings(),
            boundSql.getParameterObject());
    ParameterHandler parameterHandler =
        new DefaultParameterHandler(ms, boundSql.getParameterObject(), countBoundSql);
    PreparedStatement stmt = null;
    ResultSet rs = null;
    int count = 0;
    try {
      stmt = conn.prepareStatement(countSql);
      // 通过parameterHandler给PreparedStatement对象设置参数
      parameterHandler.setParameters(stmt);
      rs = stmt.executeQuery();
      if (rs.next()) {
        count = rs.getInt(1);
      }
    } finally {
      CloseableUtil.closeQuietly(rs);
      CloseableUtil.closeQuietly(stmt);
    }
    return count;
  }