Java Code Examples for org.apache.ibatis.mapping.ParameterMapping

The following examples show how to use org.apache.ibatis.mapping.ParameterMapping. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: mybatis   Source File: ExecutorTestHelper.java    License: Apache License 2.0 6 votes vote down vote up
public static MappedStatement createSelectAuthorWithIDof99MappedStatement(final Configuration config) {
  final TypeHandlerRegistry registry = config.getTypeHandlerRegistry();
  MappedStatement ms = new MappedStatement.Builder(config, "selectAuthor", new StaticSqlSource(config,"SELECT * FROM author WHERE id = 99"), SqlCommandType.SELECT)
      .statementType(StatementType.STATEMENT)
      .parameterMap(new ParameterMap.Builder(config, "defaultParameterMap", Author.class, new ArrayList<ParameterMapping>()).build())
      .resultMaps(new ArrayList<ResultMap>() {
        {
          add(new ResultMap.Builder(config, "defaultResultMap", Author.class, new ArrayList<ResultMapping>() {
            {
              add(new ResultMapping.Builder(config, "id", "id", registry.getTypeHandler(int.class)).build());
              add(new ResultMapping.Builder(config, "username", "username", registry.getTypeHandler(String.class)).build());
              add(new ResultMapping.Builder(config, "password", "password", registry.getTypeHandler(String.class)).build());
              add(new ResultMapping.Builder(config, "email", "email", registry.getTypeHandler(String.class)).build());
              add(new ResultMapping.Builder(config, "bio", "bio", registry.getTypeHandler(String.class)).build());
            }
          }).build());
        }
      }).build();
  return ms;
}
 
Example 2
Source Project: das   Source File: TransController.java    License: Apache License 2.0 6 votes vote down vote up
private LinkedHashMap<String, String> getParams(List<ParameterMapping> parameterMappings) {
    LinkedHashMap<String, String> parsedParams = newLinkedHashMap();
    for(ParameterMapping mapping : parameterMappings) {
        String type;
        if(mapping.getJavaType() != Object.class) {
            type = mapping.getJavaType().getSimpleName().toLowerCase();
        } else {
            if(mapping.getJdbcType() == null) {
                type = "object";
            } else {
                type = mapping.getJdbcType().name().toLowerCase();
            }
        }
        parsedParams.put(mapping.getProperty(), type);
    }
    return parsedParams;
}
 
Example 3
Source Project: mybatis-boost   Source File: ListParameterEnhancement.java    License: MIT License 6 votes vote down vote up
private Map<Integer, List<?>> getLists(Object parameterObject, List<ParameterMapping> parameterMappings) {
    if (parameterMappings.isEmpty()) {
        return Collections.emptyMap();
    } else {
        Map<Integer, List<?>> listMap = new HashMap<>();
        MetaObject parameterMetaObject = MyBatisUtils.getMetaObject(parameterObject);
        for (int i = 0; i < parameterMappings.size(); i++) {
            try {
                Object property = parameterMetaObject.getValue(parameterMappings.get(i).getProperty());
                if (property instanceof List) {
                    listMap.put(i, (List<?>) property);
                }
            } catch (Exception ignored) {
                return Collections.emptyMap();
            }
        }
        return listMap;
    }
}
 
Example 4
Source Project: dynamic-add-date   Source File: AddDateInterceptor.java    License: MIT License 6 votes vote down vote up
/**
 * 解决原始sql语句已包含自动添加的列导致参数数量映射异常的问题
 *
 * @param boundSql
 */
private void handleParameterMapping(BoundSql boundSql) {
    List<ParameterMapping> parameterMappingList = boundSql.getParameterMappings();
    Iterator<ParameterMapping> it = parameterMappingList.iterator();
    String camelCaseCreateDateProperty = StringUtil.camelCase(createDateColumnName);
    String camelCaseUpdateDateProperty = StringUtil.camelCase(updateDateColumnName);
    while (it.hasNext()) {
        ParameterMapping pm = it.next();
        if (pm.getProperty().equals(camelCaseCreateDateProperty)) {
            log.debug("原始Sql语句已包含自动添加的列: {}", createDateColumnName);
            it.remove();
        }
        if (pm.getProperty().equals(camelCaseUpdateDateProperty)) {
            log.debug("原始Sql语句已包含自动添加的列: {}", updateDateColumnName);
            it.remove();
        }
    }
}
 
Example 5
Source Project: mybaties   Source File: MapperBuilderAssistant.java    License: Apache License 2.0 6 votes vote down vote up
public ParameterMapping buildParameterMapping(
    Class<?> parameterType,
    String property,
    Class<?> javaType,
    JdbcType jdbcType,
    String resultMap,
    ParameterMode parameterMode,
    Class<? extends TypeHandler<?>> typeHandler,
    Integer numericScale) {
  resultMap = applyCurrentNamespace(resultMap, true);

  // Class parameterType = parameterMapBuilder.type();
  Class<?> javaTypeClass = resolveParameterJavaType(parameterType, property, javaType, jdbcType);
  TypeHandler<?> typeHandlerInstance = resolveTypeHandler(javaTypeClass, typeHandler);

  ParameterMapping.Builder builder = new ParameterMapping.Builder(configuration, property, javaTypeClass);
  builder.jdbcType(jdbcType);
  builder.resultMapId(resultMap);
  builder.mode(parameterMode);
  builder.numericScale(numericScale);
  builder.typeHandler(typeHandlerInstance);
  return builder.build();
}
 
Example 6
Source Project: mybaties   Source File: XMLMapperBuilder.java    License: Apache License 2.0 6 votes vote down vote up
private void parameterMapElement(List<XNode> list) throws Exception {
  for (XNode parameterMapNode : list) {
    String id = parameterMapNode.getStringAttribute("id");
    String type = parameterMapNode.getStringAttribute("type");
    Class<?> parameterClass = resolveClass(type);
    List<XNode> parameterNodes = parameterMapNode.evalNodes("parameter");
    List<ParameterMapping> parameterMappings = new ArrayList<ParameterMapping>();
    for (XNode parameterNode : parameterNodes) {
      String property = parameterNode.getStringAttribute("property");
      String javaType = parameterNode.getStringAttribute("javaType");
      String jdbcType = parameterNode.getStringAttribute("jdbcType");
      String resultMap = parameterNode.getStringAttribute("resultMap");
      String mode = parameterNode.getStringAttribute("mode");
      String typeHandler = parameterNode.getStringAttribute("typeHandler");
      Integer numericScale = parameterNode.getIntAttribute("numericScale");
      ParameterMode modeEnum = resolveParameterMode(mode);
      Class<?> javaTypeClass = resolveClass(javaType);
      JdbcType jdbcTypeEnum = resolveJdbcType(jdbcType);
      @SuppressWarnings("unchecked")
      Class<? extends TypeHandler<?>> typeHandlerClass = (Class<? extends TypeHandler<?>>) resolveClass(typeHandler);
      ParameterMapping parameterMapping = builderAssistant.buildParameterMapping(parameterClass, property, javaTypeClass, jdbcTypeEnum, resultMap, modeEnum, typeHandlerClass, numericScale);
      parameterMappings.add(parameterMapping);
    }
    builderAssistant.addParameterMap(id, parameterClass, parameterMappings);
  }
}
 
Example 7
Source Project: mybaties   Source File: BaseExecutor.java    License: Apache License 2.0 6 votes vote down vote up
private void handleLocallyCachedOutputParameters(MappedStatement ms, CacheKey key, Object parameter, BoundSql boundSql) {
  //处理存储过程的OUT参数
  if (ms.getStatementType() == StatementType.CALLABLE) {
    final Object cachedParameter = localOutputParameterCache.getObject(key);
    if (cachedParameter != null && parameter != null) {
      final MetaObject metaCachedParameter = configuration.newMetaObject(cachedParameter);
      final MetaObject metaParameter = configuration.newMetaObject(parameter);
      for (ParameterMapping parameterMapping : boundSql.getParameterMappings()) {
        if (parameterMapping.getMode() != ParameterMode.IN) {
          final String parameterName = parameterMapping.getProperty();
          final Object cachedValue = metaCachedParameter.getValue(parameterName);
          metaParameter.setValue(parameterName, cachedValue);
        }
      }
    }
  }
}
 
Example 8
Source Project: mybaties   Source File: DefaultResultSetHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void handleOutputParameters(CallableStatement cs) throws SQLException {
  final Object parameterObject = parameterHandler.getParameterObject();
  final MetaObject metaParam = configuration.newMetaObject(parameterObject);
  final List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
  //循环处理每个参数
  for (int i = 0; i < parameterMappings.size(); i++) {
    final ParameterMapping parameterMapping = parameterMappings.get(i);
    //只处理OUT|INOUT
    if (parameterMapping.getMode() == ParameterMode.OUT || parameterMapping.getMode() == ParameterMode.INOUT) {
      if (ResultSet.class.equals(parameterMapping.getJavaType())) {
        //如果是ResultSet型(游标)
        //#{result, jdbcType=CURSOR, mode=OUT, javaType=ResultSet, resultMap=userResultMap}
        //先用CallableStatement.getObject取得这个游标,作为参数传进去
        handleRefCursorOutputParameter((ResultSet) cs.getObject(i + 1), parameterMapping, metaParam);
      } else {
        //否则是普通型,核心就是CallableStatement.getXXX取得值
        final TypeHandler<?> typeHandler = parameterMapping.getTypeHandler();
        metaParam.setValue(parameterMapping.getProperty(), typeHandler.getResult(cs, i + 1));
      }
    }
  }
}
 
Example 9
Source Project: mybaties   Source File: CallableStatementHandler.java    License: Apache License 2.0 6 votes vote down vote up
private void registerOutputParameters(CallableStatement cs) throws SQLException {
  List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
  for (int i = 0, n = parameterMappings.size(); i < n; i++) {
    ParameterMapping parameterMapping = parameterMappings.get(i);
    //只处理OUT|INOUT
    if (parameterMapping.getMode() == ParameterMode.OUT || parameterMapping.getMode() == ParameterMode.INOUT) {
      if (null == parameterMapping.getJdbcType()) {
        throw new ExecutorException("The JDBC Type must be specified for output parameter.  Parameter: " + parameterMapping.getProperty());
      } else {
        if (parameterMapping.getNumericScale() != null && (parameterMapping.getJdbcType() == JdbcType.NUMERIC || parameterMapping.getJdbcType() == JdbcType.DECIMAL)) {
          cs.registerOutParameter(i + 1, parameterMapping.getJdbcType().TYPE_CODE, parameterMapping.getNumericScale());
        } else {
          //核心是调用CallableStatement.registerOutParameter
          if (parameterMapping.getJdbcTypeName() == null) {
            cs.registerOutParameter(i + 1, parameterMapping.getJdbcType().TYPE_CODE);
          } else {
            cs.registerOutParameter(i + 1, parameterMapping.getJdbcType().TYPE_CODE, parameterMapping.getJdbcTypeName());
          }
        }
      }
    }
  }
}
 
Example 10
Source Project: mybaties   Source File: ExecutorTestHelper.java    License: Apache License 2.0 6 votes vote down vote up
public static MappedStatement prepareInsertAuthorMappedStatement(final Configuration config) {
  final TypeHandlerRegistry registry = config.getTypeHandlerRegistry();
  MappedStatement ms = new MappedStatement.Builder(config, "insertAuthor", new StaticSqlSource(config,"INSERT INTO author (id,username,password,email,bio,favourite_section) values(?,?,?,?,?,?)"), SqlCommandType.INSERT)
      .parameterMap(
          new ParameterMap.Builder(
              config, "defaultParameterMap", Author.class,
              new ArrayList<ParameterMapping>() {
                {
                  add(new ParameterMapping.Builder(config, "id", registry.getTypeHandler(int.class)).build());
                  add(new ParameterMapping.Builder(config, "username", registry.getTypeHandler(String.class)).build());
                  add(new ParameterMapping.Builder(config, "password", registry.getTypeHandler(String.class)).build());
                  add(new ParameterMapping.Builder(config, "email", registry.getTypeHandler(String.class)).build());
                  add(new ParameterMapping.Builder(config, "bio", registry.getTypeHandler(String.class)).jdbcType(JdbcType.VARCHAR).build());
                  add(new ParameterMapping.Builder(config, "favouriteSection", registry.getTypeHandler(Section.class)).jdbcType(JdbcType.VARCHAR).build());
                }
              }).build())
      .cache(authorCache).build();
  return ms;
}
 
Example 11
Source Project: mybaties   Source File: ExecutorTestHelper.java    License: Apache License 2.0 6 votes vote down vote up
public static MappedStatement prepareInsertAuthorMappedStatementWithAutoKey(final Configuration config) {
  final TypeHandlerRegistry registry = config.getTypeHandlerRegistry();
  MappedStatement ms = new MappedStatement.Builder(config, "insertAuthor", new StaticSqlSource(config,"INSERT INTO author (username,password,email,bio,favourite_section) values(?,?,?,?,?)"), SqlCommandType.INSERT)
      .parameterMap(
          new ParameterMap.Builder(config, "defaultParameterMap", Author.class, new ArrayList<ParameterMapping>() {
            {
              add(new ParameterMapping.Builder(config, "username", registry.getTypeHandler(String.class)).build());
              add(new ParameterMapping.Builder(config, "password", registry.getTypeHandler(String.class)).build());
              add(new ParameterMapping.Builder(config, "email", registry.getTypeHandler(String.class)).build());
              add(new ParameterMapping.Builder(config, "bio", registry.getTypeHandler(String.class)).jdbcType(JdbcType.VARCHAR).build());
              add(new ParameterMapping.Builder(config, "favouriteSection", registry.getTypeHandler(Section.class)).jdbcType(JdbcType.VARCHAR).build());
            }
          }).build())
      .cache(authorCache)
      .keyGenerator(new Jdbc3KeyGenerator())
      .keyProperty("id")
      .build();
  return ms;
}
 
Example 12
Source Project: mybaties   Source File: ExecutorTestHelper.java    License: Apache License 2.0 6 votes vote down vote up
public static MappedStatement prepareUpdateAuthorMappedStatement(final Configuration config) {
  final TypeHandlerRegistry registry = config.getTypeHandlerRegistry();
  MappedStatement ms = new MappedStatement.Builder(config, "updateAuthor", new StaticSqlSource(config,"UPDATE author SET username = ?, password = ?, email = ?, bio = ? WHERE id = ?"), SqlCommandType.UPDATE)
      .parameterMap(new ParameterMap.Builder(config, "defaultParameterMap", Author.class,
          new ArrayList<ParameterMapping>() {
            {
              add(new ParameterMapping.Builder(config, "username", registry.getTypeHandler(String.class)).build());
              add(new ParameterMapping.Builder(config, "password", registry.getTypeHandler(String.class)).build());
              add(new ParameterMapping.Builder(config, "email", registry.getTypeHandler(String.class)).build());
              add(new ParameterMapping.Builder(config, "bio", registry.getTypeHandler(String.class)).jdbcType(JdbcType.VARCHAR).build());
              add(new ParameterMapping.Builder(config, "id", registry.getTypeHandler(int.class)).build());
            }
          }).build())
      .cache(authorCache).build();
  return ms;
}
 
Example 13
Source Project: mybatis   Source File: ExecutorTestHelper.java    License: Apache License 2.0 6 votes vote down vote up
public static MappedStatement prepareUpdateAuthorMappedStatement(final Configuration config) {
  final TypeHandlerRegistry registry = config.getTypeHandlerRegistry();
  MappedStatement ms = new MappedStatement.Builder(config, "updateAuthor", new StaticSqlSource(config,"UPDATE author SET username = ?, password = ?, email = ?, bio = ? WHERE id = ?"), SqlCommandType.UPDATE)
      .parameterMap(new ParameterMap.Builder(config, "defaultParameterMap", Author.class,
          new ArrayList<ParameterMapping>() {
            {
              add(new ParameterMapping.Builder(config, "username", registry.getTypeHandler(String.class)).build());
              add(new ParameterMapping.Builder(config, "password", registry.getTypeHandler(String.class)).build());
              add(new ParameterMapping.Builder(config, "email", registry.getTypeHandler(String.class)).build());
              add(new ParameterMapping.Builder(config, "bio", registry.getTypeHandler(String.class)).jdbcType(JdbcType.VARCHAR).build());
              add(new ParameterMapping.Builder(config, "id", registry.getTypeHandler(int.class)).build());
            }
          }).build())
      .cache(authorCache).build();
  return ms;
}
 
Example 14
Source Project: mybaties   Source File: ExecutorTestHelper.java    License: Apache License 2.0 6 votes vote down vote up
public static MappedStatement prepareSelectAuthorViaOutParams(final Configuration config) {
  final TypeHandlerRegistry registry = config.getTypeHandlerRegistry();
  MappedStatement ms = new MappedStatement.Builder(config, "selectAuthorViaOutParams", new StaticSqlSource(config, "{call selectAuthorViaOutParams(?,?,?,?,?)}"), SqlCommandType.SELECT)
      .statementType(StatementType.CALLABLE)
      .parameterMap(new ParameterMap.Builder(config, "defaultParameterMap", Author.class,
          new ArrayList<ParameterMapping>() {
            {
              add(new ParameterMapping.Builder(config, "id", registry.getTypeHandler(int.class)).build());
              add(new ParameterMapping.Builder(config, "username", registry.getTypeHandler(String.class)).jdbcType(JdbcType.VARCHAR).mode(ParameterMode.OUT).build());
              add(new ParameterMapping.Builder(config, "password", registry.getTypeHandler(String.class)).jdbcType(JdbcType.VARCHAR).mode(ParameterMode.OUT).build());
              add(new ParameterMapping.Builder(config, "email", registry.getTypeHandler(String.class)).jdbcType(JdbcType.VARCHAR).mode(ParameterMode.OUT).build());
              add(new ParameterMapping.Builder(config, "bio", registry.getTypeHandler(String.class)).jdbcType(JdbcType.VARCHAR).mode(ParameterMode.OUT).build());
            }
          }).build())
      .resultMaps(new ArrayList<ResultMap>())
      .cache(authorCache).build();
  return ms;
}
 
Example 15
Source Project: mybaties   Source File: ExecutorTestHelper.java    License: Apache License 2.0 6 votes vote down vote up
public static MappedStatement createSelectAuthorWithIDof99MappedStatement(final Configuration config) {
  final TypeHandlerRegistry registry = config.getTypeHandlerRegistry();
  MappedStatement ms = new MappedStatement.Builder(config, "selectAuthor", new StaticSqlSource(config,"SELECT * FROM author WHERE id = 99"), SqlCommandType.SELECT)
      .statementType(StatementType.STATEMENT)
      .parameterMap(new ParameterMap.Builder(config, "defaultParameterMap", Author.class, new ArrayList<ParameterMapping>()).build())
      .resultMaps(new ArrayList<ResultMap>() {
        {
          add(new ResultMap.Builder(config, "defaultResultMap", Author.class, new ArrayList<ResultMapping>() {
            {
              add(new ResultMapping.Builder(config, "id", "id", registry.getTypeHandler(int.class)).build());
              add(new ResultMapping.Builder(config, "username", "username", registry.getTypeHandler(String.class)).build());
              add(new ResultMapping.Builder(config, "password", "password", registry.getTypeHandler(String.class)).build());
              add(new ResultMapping.Builder(config, "email", "email", registry.getTypeHandler(String.class)).build());
              add(new ResultMapping.Builder(config, "bio", "bio", registry.getTypeHandler(String.class)).build());
            }
          }).build());
        }
      }).build();
  return ms;
}
 
Example 16
Source Project: mybatis   Source File: MapperBuilderAssistant.java    License: Apache License 2.0 6 votes vote down vote up
public ParameterMapping buildParameterMapping(
    Class<?> parameterType,
    String property,
    Class<?> javaType,
    JdbcType jdbcType,
    String resultMap,
    ParameterMode parameterMode,
    Class<? extends TypeHandler<?>> typeHandler,
    Integer numericScale) {
  resultMap = applyCurrentNamespace(resultMap, true);

  // Class parameterType = parameterMapBuilder.type();
  Class<?> javaTypeClass = resolveParameterJavaType(parameterType, property, javaType, jdbcType);
  TypeHandler<?> typeHandlerInstance = resolveTypeHandler(javaTypeClass, typeHandler);

  ParameterMapping.Builder builder = new ParameterMapping.Builder(configuration, property, javaTypeClass);
  builder.jdbcType(jdbcType);
  builder.resultMapId(resultMap);
  builder.mode(parameterMode);
  builder.numericScale(numericScale);
  builder.typeHandler(typeHandlerInstance);
  return builder.build();
}
 
Example 17
Source Project: mybatis   Source File: MapperBuilderAssistant.java    License: Apache License 2.0 6 votes vote down vote up
private void setStatementParameterMap(
    String parameterMap,
    Class<?> parameterTypeClass,
    MappedStatement.Builder statementBuilder) {
  parameterMap = applyCurrentNamespace(parameterMap, true);

  if (parameterMap != null) {
    try {
      statementBuilder.parameterMap(configuration.getParameterMap(parameterMap));
    } catch (IllegalArgumentException e) {
      throw new IncompleteElementException("Could not find parameter map " + parameterMap, e);
    }
  } else if (parameterTypeClass != null) {
    List<ParameterMapping> parameterMappings = new ArrayList<ParameterMapping>();
    ParameterMap.Builder inlineParameterMapBuilder = new ParameterMap.Builder(
        configuration,
        statementBuilder.id() + "-Inline",
        parameterTypeClass,
        parameterMappings);
    statementBuilder.parameterMap(inlineParameterMapBuilder.build());
  }
}
 
Example 18
Source Project: mybatis   Source File: XMLMapperBuilder.java    License: Apache License 2.0 6 votes vote down vote up
private void parameterMapElement(List<XNode> list) throws Exception {
  for (XNode parameterMapNode : list) {
    String id = parameterMapNode.getStringAttribute("id");
    String type = parameterMapNode.getStringAttribute("type");
    Class<?> parameterClass = resolveClass(type);
    List<XNode> parameterNodes = parameterMapNode.evalNodes("parameter");
    List<ParameterMapping> parameterMappings = new ArrayList<ParameterMapping>();
    for (XNode parameterNode : parameterNodes) {
      String property = parameterNode.getStringAttribute("property");
      String javaType = parameterNode.getStringAttribute("javaType");
      String jdbcType = parameterNode.getStringAttribute("jdbcType");
      String resultMap = parameterNode.getStringAttribute("resultMap");
      String mode = parameterNode.getStringAttribute("mode");
      String typeHandler = parameterNode.getStringAttribute("typeHandler");
      Integer numericScale = parameterNode.getIntAttribute("numericScale");
      ParameterMode modeEnum = resolveParameterMode(mode);
      Class<?> javaTypeClass = resolveClass(javaType);
      JdbcType jdbcTypeEnum = resolveJdbcType(jdbcType);
      @SuppressWarnings("unchecked")
      Class<? extends TypeHandler<?>> typeHandlerClass = (Class<? extends TypeHandler<?>>) resolveClass(typeHandler);
      ParameterMapping parameterMapping = builderAssistant.buildParameterMapping(parameterClass, property, javaTypeClass, jdbcTypeEnum, resultMap, modeEnum, typeHandlerClass, numericScale);
      parameterMappings.add(parameterMapping);
    }
    builderAssistant.addParameterMap(id, parameterClass, parameterMappings);
  }
}
 
Example 19
Source Project: mybatis   Source File: BaseExecutor.java    License: Apache License 2.0 6 votes vote down vote up
private void handleLocallyCachedOutputParameters(MappedStatement ms, CacheKey key, Object parameter, BoundSql boundSql) {
  //处理存储过程的OUT参数
  if (ms.getStatementType() == StatementType.CALLABLE) {
    final Object cachedParameter = localOutputParameterCache.getObject(key);
    if (cachedParameter != null && parameter != null) {
      final MetaObject metaCachedParameter = configuration.newMetaObject(cachedParameter);
      final MetaObject metaParameter = configuration.newMetaObject(parameter);
      for (ParameterMapping parameterMapping : boundSql.getParameterMappings()) {
        if (parameterMapping.getMode() != ParameterMode.IN) {
          final String parameterName = parameterMapping.getProperty();
          final Object cachedValue = metaCachedParameter.getValue(parameterName);
          metaParameter.setValue(parameterName, cachedValue);
        }
      }
    }
  }
}
 
Example 20
Source Project: mybatis   Source File: DefaultResultSetHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void handleOutputParameters(CallableStatement cs) throws SQLException {
  final Object parameterObject = parameterHandler.getParameterObject();
  final MetaObject metaParam = configuration.newMetaObject(parameterObject);
  final List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
  //循环处理每个参数
  for (int i = 0; i < parameterMappings.size(); i++) {
    final ParameterMapping parameterMapping = parameterMappings.get(i);
    //只处理OUT|INOUT
    if (parameterMapping.getMode() == ParameterMode.OUT || parameterMapping.getMode() == ParameterMode.INOUT) {
      if (ResultSet.class.equals(parameterMapping.getJavaType())) {
        //如果是ResultSet型(游标)
        //#{result, jdbcType=CURSOR, mode=OUT, javaType=ResultSet, resultMap=userResultMap}
        //先用CallableStatement.getObject取得这个游标,作为参数传进去
        handleRefCursorOutputParameter((ResultSet) cs.getObject(i + 1), parameterMapping, metaParam);
      } else {
        //否则是普通型,核心就是CallableStatement.getXXX取得值
        final TypeHandler<?> typeHandler = parameterMapping.getTypeHandler();
        metaParam.setValue(parameterMapping.getProperty(), typeHandler.getResult(cs, i + 1));
      }
    }
  }
}
 
Example 21
Source Project: mybatis   Source File: CallableStatementHandler.java    License: Apache License 2.0 6 votes vote down vote up
private void registerOutputParameters(CallableStatement cs) throws SQLException {
  List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
  for (int i = 0, n = parameterMappings.size(); i < n; i++) {
    ParameterMapping parameterMapping = parameterMappings.get(i);
    //只处理OUT|INOUT
    if (parameterMapping.getMode() == ParameterMode.OUT || parameterMapping.getMode() == ParameterMode.INOUT) {
      if (null == parameterMapping.getJdbcType()) {
        throw new ExecutorException("The JDBC Type must be specified for output parameter.  Parameter: " + parameterMapping.getProperty());
      } else {
        if (parameterMapping.getNumericScale() != null && (parameterMapping.getJdbcType() == JdbcType.NUMERIC || parameterMapping.getJdbcType() == JdbcType.DECIMAL)) {
          cs.registerOutParameter(i + 1, parameterMapping.getJdbcType().TYPE_CODE, parameterMapping.getNumericScale());
        } else {
          //核心是调用CallableStatement.registerOutParameter
          if (parameterMapping.getJdbcTypeName() == null) {
            cs.registerOutParameter(i + 1, parameterMapping.getJdbcType().TYPE_CODE);
          } else {
            cs.registerOutParameter(i + 1, parameterMapping.getJdbcType().TYPE_CODE, parameterMapping.getJdbcTypeName());
          }
        }
      }
    }
  }
}
 
Example 22
Source Project: Mybatis-PageHelper   Source File: HerdDBDialect.java    License: MIT License 6 votes vote down vote up
@Override
public Object processPageParameter(MappedStatement ms, Map<String, Object> paramMap, Page page, BoundSql boundSql, CacheKey pageKey) {
    paramMap.put(PAGEPARAMETER_FIRST, page.getStartRow());
    paramMap.put(PAGEPARAMETER_SECOND, page.getPageSize());
    pageKey.update(page.getStartRow());
    pageKey.update(page.getPageSize());
    if (boundSql.getParameterMappings() != null) {
        List<ParameterMapping> newParameterMappings = new ArrayList<ParameterMapping>(boundSql.getParameterMappings());
        if (page.getStartRow() == 0) {
            newParameterMappings.add(new ParameterMapping.Builder(ms.getConfiguration(), PAGEPARAMETER_SECOND, Integer.class).build());
        } else {
            newParameterMappings.add(new ParameterMapping.Builder(ms.getConfiguration(), PAGEPARAMETER_FIRST, Integer.class).build());
            newParameterMappings.add(new ParameterMapping.Builder(ms.getConfiguration(), PAGEPARAMETER_SECOND, Integer.class).build());
        }
        MetaObject metaObject = MetaObjectUtil.forObject(boundSql);
        metaObject.setValue("parameterMappings", newParameterMappings);
    }
    return paramMap;
}
 
Example 23
@Override
public int setBeforeSubqueryParameters(PreparedStatement statement, QueryParameters queryParameters, int startIndex) throws SQLException {
    // find before parameters
    final List<ParameterMapping> parameterMappings = this.boundSql.getParameterMappings();
    List<ParameterMapping> before = Collects.limit(parameterMappings, queryParameters.getBeforeSubqueryParameterCount());
    setParameters(statement, before, startIndex, getEscapeLikeParametersIndexes());
    return queryParameters.getBeforeSubqueryParameterCount();
}
 
Example 24
@Override
public int setAfterSubqueryParameters(PreparedStatement statement, QueryParameters queryParameters, int startIndex) throws SQLException {
    final List<ParameterMapping> parameterMappings = this.boundSql.getParameterMappings();
    List<ParameterMapping> after = Collects.skip(parameterMappings, parameterMappings.size() - queryParameters.getAfterSubqueryParameterCount());
    setParameters(statement, after, startIndex, getEscapeLikeParametersIndexes());
    return queryParameters.getBeforeSubqueryParameterCount();
}
 
Example 25
Source Project: mybatis-boost   Source File: MetricInterceptor.java    License: MIT License 5 votes vote down vote up
@Override
public Object intercept(Invocation invocation) throws Throwable {
    BoundSql boundSql = ((StatementHandler) invocation.getTarget()).getBoundSql();

    String sql = boundSql.getSql().replaceAll("\\s*\\n\\s*", " ");
    List<Object> parameters = new ArrayList<>();
    if (configuration.isShowQueryWithParameters()) {
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        Object parameterObject = boundSql.getParameterObject();
        MetaObject metaObject = MyBatisUtils.getMetaObject(parameterObject);
        if (parameterMappings.size() == 1 && !(parameterObject instanceof Map) &&
                !metaObject.hasGetter(parameterMappings.get(0).getProperty())) {
            parameters.add(parameterObject);
        } else {
            parameterMappings.forEach(pm -> parameters.add(metaObject.getValue(pm.getProperty())));
        }
    }

    StopWatch stopWatch = StopWatch.createStarted();
    Object proceed = invocation.proceed();
    long time = stopWatch.getTime();
    if (time > configuration.getSlowQueryThresholdInMillis()) {
        if (parameters.isEmpty()) {
            logger.error(String.format("[SLOW Query took %s ms] %s", time, sql));
        } else {
            logger.error(String.format("[SLOW Query took %s ms, Parameters: %s] %s ", time, parameters, sql));
        }
        BiConsumer<String, Long> slowSqlHandler = configuration.getSlowQueryHandler();
        if (slowSqlHandler != null) {
            slowSqlHandler.accept(sql, time);
        }
    } else if (configuration.isShowQuery()) {
        if (parameters.isEmpty()) {
            logger.info(String.format("[Query took %s ms] %s", time, sql));
        } else {
            logger.info(String.format("[Query took %s ms, Parameters: %s] %s ", time, parameters, sql));
        }
    }
    return proceed;
}
 
Example 26
Source Project: mybatis   Source File: ExecutorTestHelper.java    License: Apache License 2.0 5 votes vote down vote up
public static MappedStatement prepareComplexSelectBlogMappedStatement(final Configuration config) {
  final TypeHandlerRegistry registry = config.getTypeHandlerRegistry();
  final SqlSource sqlSource = new StaticSqlSource(config, "SELECT b.id, b.author_id, b.title, a.username, a.password, a.email, a.bio" +
      " FROM blog b" +
      " INNER JOIN author a ON b.author_id = a.id" +
      " WHERE b.id = ?");
  final ParameterMap parameterMap = new ParameterMap.Builder(config, "defaultParameterMap", int.class,
      new ArrayList<ParameterMapping>() {
        {
          add(new ParameterMapping.Builder(config, "id", registry.getTypeHandler(int.class)).build());
        }
      }).build();
  final ResultMap resultMap = new ResultMap.Builder(config, "defaultResultMap", Blog.class, new ArrayList<ResultMapping>() {
    {
      add(new ResultMapping.Builder(config, "id", "id", registry.getTypeHandler(int.class))
          .flags(new ArrayList<ResultFlag>() {
            {
              add(ResultFlag.ID);
            }
          }).build());
      add(new ResultMapping.Builder(config, "title", "title", registry.getTypeHandler(String.class)).build());
      add(new ResultMapping.Builder(config, "author.id", "author_id", registry.getTypeHandler(int.class)).build());
      add(new ResultMapping.Builder(config, "author.username", "username", registry.getTypeHandler(String.class)).build());
      add(new ResultMapping.Builder(config, "author.password", "password", registry.getTypeHandler(String.class)).build());
      add(new ResultMapping.Builder(config, "author.email", "email", registry.getTypeHandler(String.class)).build());
      add(new ResultMapping.Builder(config, "author.bio", "bio", registry.getTypeHandler(String.class)).build());
      add(new ResultMapping.Builder(config, "posts", "id", registry.getTypeHandler(int.class)).javaType(List.class).nestedQueryId("selectPostsForBlog").build());
    }
  }).build();

  return new MappedStatement.Builder(config, "selectBlogById", sqlSource, SqlCommandType.SELECT)
      .parameterMap(parameterMap)
      .resultMaps(new ArrayList<ResultMap>() {
        {
          add(resultMap);
        }
      }).build();
}
 
Example 27
Source Project: mybatis-boost   Source File: NullEnhancement.java    License: MIT License 5 votes vote down vote up
@Override
public void replace(Connection connection, MetaObject metaObject, MappedStatement mappedStatement, BoundSql boundSql) {
    if (mappedStatement.getSqlCommandType() == SqlCommandType.SELECT ||
            mappedStatement.getSqlCommandType() == SqlCommandType.DELETE) {
        String sql = boundSql.getSql();

        Matcher matcher = SqlUtils.PATTERN_PLACEHOLDER.matcher(sql);
        Iterator<ParameterMapping> iterator = boundSql.getParameterMappings().iterator();
        MetaObject parameterMetaObject = MyBatisUtils.getMetaObject(boundSql.getParameterObject());
        boolean isUpperCase = Character.isUpperCase(sql.charAt(0));

        int offset = 0;
        StringBuilder sqlBuilder = new StringBuilder();
        while (matcher.find() & iterator.hasNext()) {
            try {
                if (parameterMetaObject.getValue(iterator.next().getProperty()) != null) continue;
            } catch (Exception ignored) {
                continue;
            }
            iterator.remove();

            String substring = sql.substring(offset, matcher.end());
            int before = substring.length();
            substring = substring.replaceFirst(" ?!= *\\?$| ?<> *\\?$",
                    isUpperCase ? " IS NOT NULL" : " is not null");
            if (substring.length() == before) {
                substring = substring.replaceFirst(" ?= *\\?$", isUpperCase ? " IS NULL" : " is null");
            }
            sqlBuilder.append(substring);
            offset = matcher.end();
        }
        sqlBuilder.append(sql, offset, sql.length());
        metaObject.setValue("delegate.boundSql.sql", sqlBuilder.toString());
    }
}
 
Example 28
Source Project: mybatis-boost   Source File: UpdateEnhancement.java    License: MIT License 5 votes vote down vote up
private List<String> getConditionProperties(Class<?> entityType, List<ParameterMapping> parameterMappings) {
    List<String> conditionProperties = parameterMappings.stream()
            .map(ParameterMapping::getProperty).collect(Collectors.toList());
    try {
        String idProperty = EntityUtils.getIdProperty(entityType);
        if (!conditionProperties.contains(idProperty)) {
            conditionProperties.add(idProperty);
        }
    } catch (NoSuchFieldError ignored) {
    }
    return conditionProperties;
}
 
Example 29
Source Project: mybatis-boost   Source File: UpdateEnhancement.java    License: MIT License 5 votes vote down vote up
private List<ParameterMapping> getParameterMappings(MetaObject metaObject, BoundSql boundSql, List<String> properties) {
    org.apache.ibatis.session.Configuration configuration = (org.apache.ibatis.session.Configuration)
            metaObject.getValue("delegate.configuration");
    List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
    Object parameterObject = boundSql.getParameterObject();
    if (parameterObject instanceof Map) {
        for (int i = 1; i <= properties.size(); i++) {
            parameterMappings.add(i - 1,
                    new ParameterMapping.Builder(configuration, "param" + i, Object.class).build());
        }
    } else {
        parameterMappings.addAll(0, MyBatisUtils.getParameterMappings(configuration, properties));
    }
    return parameterMappings;
}
 
Example 30
Source Project: mybatis-boost   Source File: MyBatisUtils.java    License: MIT License 5 votes vote down vote up
public static List<ParameterMapping> getListParameterMappings
        (Configuration configuration, List<String> properties, int size) {
    List<ParameterMapping> parameterMappings = new ArrayList<>(properties.size() * size);
    for (int i = 0; i < size; i++) {
        for (String property : properties) {
            parameterMappings.add(new ParameterMapping.Builder
                    (configuration, "list[" + i + "]." + property, Object.class).build());
        }
    }
    return parameterMappings;
}