org.apache.ibatis.type.TypeHandler Java Examples

The following examples show how to use org.apache.ibatis.type.TypeHandler. 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 File: DefaultResultSetHandler.java    From mybaties with Apache License 2.0 6 votes vote down vote up
private Object createByConstructorSignature(ResultSetWrapper rsw, Class<?> resultType, List<Class<?>> constructorArgTypes, List<Object> constructorArgs,
    String columnPrefix) throws SQLException {
  for (Constructor<?> constructor : resultType.getDeclaredConstructors()) {
    if (typeNames(constructor.getParameterTypes()).equals(rsw.getClassNames())) {
      boolean foundValues = false;
      for (int i = 0; i < constructor.getParameterTypes().length; i++) {
        Class<?> parameterType = constructor.getParameterTypes()[i];
        String columnName = rsw.getColumnNames().get(i);
        TypeHandler<?> typeHandler = rsw.getTypeHandler(parameterType, columnName);
        Object value = typeHandler.getResult(rsw.getResultSet(), prependPrefix(columnName, columnPrefix));
        constructorArgTypes.add(parameterType);
        constructorArgs.add(value);
        foundValues = value != null || foundValues;
      }
      //上面是构造函数创建对象,下面是对象工厂来创建
      return foundValues ? objectFactory.create(resultType, constructorArgTypes, constructorArgs) : null;
    }
  }
  throw new ExecutorException("No constructor found in " + resultType.getName() + " matching " + rsw.getClassNames());
}
 
Example #2
Source File: SqlRunner.java    From mybaties with Apache License 2.0 6 votes vote down vote up
private void setParameters(PreparedStatement ps, Object... args) throws SQLException {
  for (int i = 0, n = args.length; i < n; i++) {
    if (args[i] == null) {
      throw new SQLException("SqlRunner requires an instance of Null to represent typed null values for JDBC compatibility");
    } else if (args[i] instanceof Null) {
      ((Null) args[i]).getTypeHandler().setParameter(ps, i + 1, null, ((Null) args[i]).getJdbcType());
    } else {
  	//巧妙的利用TypeHandler来设置参数
      TypeHandler typeHandler = typeHandlerRegistry.getTypeHandler(args[i].getClass());
      if (typeHandler == null) {
        throw new SQLException("SqlRunner could not find a TypeHandler instance for " + args[i].getClass());
      } else {
        typeHandler.setParameter(ps, i + 1, args[i], null);
      }
    }
  }
}
 
Example #3
Source File: MapperBuilderAssistant.java    From mybaties with 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 #4
Source File: XMLMapperBuilder.java    From mybaties with 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 #5
Source File: SqlRunner.java    From mybatis with Apache License 2.0 6 votes vote down vote up
private void setParameters(PreparedStatement ps, Object... args) throws SQLException {
  for (int i = 0, n = args.length; i < n; i++) {
    if (args[i] == null) {
      throw new SQLException("SqlRunner requires an instance of Null to represent typed null values for JDBC compatibility");
    } else if (args[i] instanceof Null) {
      ((Null) args[i]).getTypeHandler().setParameter(ps, i + 1, null, ((Null) args[i]).getJdbcType());
    } else {
  	//巧妙的利用TypeHandler来设置参数
      TypeHandler typeHandler = typeHandlerRegistry.getTypeHandler(args[i].getClass());
      if (typeHandler == null) {
        throw new SQLException("SqlRunner could not find a TypeHandler instance for " + args[i].getClass());
      } else {
        typeHandler.setParameter(ps, i + 1, args[i], null);
      }
    }
  }
}
 
Example #6
Source File: DefaultResultSetHandler.java    From mybatis with Apache License 2.0 6 votes vote down vote up
private Object prepareCompositeKeyParameter(ResultSet rs, ResultMapping resultMapping, Class<?> parameterType, String columnPrefix) throws SQLException {
  final Object parameterObject = instantiateParameterObject(parameterType);
  final MetaObject metaObject = configuration.newMetaObject(parameterObject);
  boolean foundValues = false;
  for (ResultMapping innerResultMapping : resultMapping.getComposites()) {
    final Class<?> propType = metaObject.getSetterType(innerResultMapping.getProperty());
    final TypeHandler<?> typeHandler = typeHandlerRegistry.getTypeHandler(propType);
    final Object propValue = typeHandler.getResult(rs, prependPrefix(innerResultMapping.getColumn(), columnPrefix));
    // issue #353 & #560 do not execute nested query if key is null
    if (propValue != null) {
      metaObject.setValue(innerResultMapping.getProperty(), propValue);
      foundValues = true;
    }
  }
  return foundValues ? parameterObject : null;
}
 
Example #7
Source File: XmlConfigBuilderTest.java    From mybatis with Apache License 2.0 6 votes vote down vote up
@Test
public void registerJavaTypeInitializingTypeHandler() {
  final String MAPPER_CONFIG = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
      + "<!DOCTYPE configuration PUBLIC \"-//mybatis.org//DTD Config 3.0//EN\" \"http://mybatis.org/dtd/mybatis-3-config.dtd\">\n" 
      + "<configuration>\n" 
      + "  <typeHandlers>\n"
      + "    <typeHandler javaType=\"org.apache.ibatis.builder.XmlConfigBuilderTest$MyEnum\"\n"
      + "      handler=\"org.apache.ibatis.builder.XmlConfigBuilderTest$EnumOrderTypeHandler\"/>\n" 
      + "  </typeHandlers>\n" 
      + "</configuration>\n";

  XMLConfigBuilder builder = new XMLConfigBuilder(new StringReader(MAPPER_CONFIG));
  builder.parse();

  TypeHandlerRegistry typeHandlerRegistry = builder.getConfiguration().getTypeHandlerRegistry();
  TypeHandler<MyEnum> typeHandler = typeHandlerRegistry.getTypeHandler(MyEnum.class);

  assertTrue(typeHandler instanceof EnumOrderTypeHandler);
  assertArrayEquals(MyEnum.values(), ((EnumOrderTypeHandler) typeHandler).constants);
}
 
Example #8
Source File: MapperBuilderAssistant.java    From mybatis with Apache License 2.0 6 votes vote down vote up
/** Backward compatibility signature */
//向后兼容方法
public ResultMapping buildResultMapping(
    Class<?> resultType,
    String property,
    String column,
    Class<?> javaType,
    JdbcType jdbcType,
    String nestedSelect,
    String nestedResultMap,
    String notNullColumn,
    String columnPrefix,
    Class<? extends TypeHandler<?>> typeHandler,
    List<ResultFlag> flags) {
    return buildResultMapping(
      resultType, property, column, javaType, jdbcType, nestedSelect, 
      nestedResultMap, notNullColumn, columnPrefix, typeHandler, flags, null, null, configuration.isLazyLoadingEnabled());
}
 
Example #9
Source File: DefaultResultSetHandler.java    From mybatis with Apache License 2.0 6 votes vote down vote up
private void createRowKeyForMappedProperties(ResultMap resultMap, ResultSetWrapper rsw, CacheKey cacheKey, List<ResultMapping> resultMappings, String columnPrefix) throws SQLException {
  for (ResultMapping resultMapping : resultMappings) {
    if (resultMapping.getNestedResultMapId() != null && resultMapping.getResultSet() == null) {
      // Issue #392
      final ResultMap nestedResultMap = configuration.getResultMap(resultMapping.getNestedResultMapId());
      createRowKeyForMappedProperties(nestedResultMap, rsw, cacheKey, nestedResultMap.getConstructorResultMappings(),
          prependPrefix(resultMapping.getColumnPrefix(), columnPrefix));
    } else if (resultMapping.getNestedQueryId() == null) {
      final String column = prependPrefix(resultMapping.getColumn(), columnPrefix);
      final TypeHandler<?> th = resultMapping.getTypeHandler();
      List<String> mappedColumnNames = rsw.getMappedColumnNames(resultMap, columnPrefix);
      // Issue #114
      if (column != null && mappedColumnNames.contains(column.toUpperCase(Locale.ENGLISH))) {
        final Object value = th.getResult(rsw.getResultSet(), column);
        if (value != null) {
          cacheKey.update(column);
          cacheKey.update(value);
        }
      }
    }
  }
}
 
Example #10
Source File: MapperAnnotationBuilder.java    From mybatis with Apache License 2.0 6 votes vote down vote up
private Discriminator applyDiscriminator(String resultMapId, Class<?> resultType, TypeDiscriminator discriminator) {
  if (discriminator != null) {
    String column = discriminator.column();
    Class<?> javaType = discriminator.javaType() == void.class ? String.class : discriminator.javaType();
    JdbcType jdbcType = discriminator.jdbcType() == JdbcType.UNDEFINED ? null : discriminator.jdbcType();
    Class<? extends TypeHandler<?>> typeHandler = discriminator.typeHandler() == UnknownTypeHandler.class ? null : discriminator.typeHandler();
    Case[] cases = discriminator.cases();
    Map<String, String> discriminatorMap = new HashMap<String, String>();
    for (Case c : cases) {
      String value = c.value();
      String caseResultMapId = resultMapId + "-" + value;
      discriminatorMap.put(value, caseResultMapId);
    }
    return assistant.buildDiscriminator(resultType, column, javaType, jdbcType, typeHandler, discriminatorMap);
  }
  return null;
}
 
Example #11
Source File: DefaultResultSetHandler.java    From mybatis with Apache License 2.0 6 votes vote down vote up
private Object createParameterizedResultObject(ResultSetWrapper rsw, Class<?> resultType, List<ResultMapping> constructorMappings,
    List<Class<?>> constructorArgTypes, List<Object> constructorArgs, String columnPrefix) throws SQLException {
  boolean foundValues = false;
  for (ResultMapping constructorMapping : constructorMappings) {
    final Class<?> parameterType = constructorMapping.getJavaType();
    final String column = constructorMapping.getColumn();
    final Object value;
    if (constructorMapping.getNestedQueryId() != null) {
      value = getNestedQueryConstructorValue(rsw.getResultSet(), constructorMapping, columnPrefix);
    } else if (constructorMapping.getNestedResultMapId() != null) {
      final ResultMap resultMap = configuration.getResultMap(constructorMapping.getNestedResultMapId());
      value = getRowValue(rsw, resultMap);
    } else {
      final TypeHandler<?> typeHandler = constructorMapping.getTypeHandler();
      value = typeHandler.getResult(rsw.getResultSet(), prependPrefix(column, columnPrefix));
    }
    constructorArgTypes.add(parameterType);
    constructorArgs.add(value);
    foundValues = value != null || foundValues;
  }
  return foundValues ? objectFactory.create(resultType, constructorArgTypes, constructorArgs) : null;
}
 
Example #12
Source File: DefaultResultSetHandler.java    From mybaties with Apache License 2.0 6 votes vote down vote up
private void createRowKeyForMappedProperties(ResultMap resultMap, ResultSetWrapper rsw, CacheKey cacheKey, List<ResultMapping> resultMappings, String columnPrefix) throws SQLException {
  for (ResultMapping resultMapping : resultMappings) {
    if (resultMapping.getNestedResultMapId() != null && resultMapping.getResultSet() == null) {
      // Issue #392
      final ResultMap nestedResultMap = configuration.getResultMap(resultMapping.getNestedResultMapId());
      createRowKeyForMappedProperties(nestedResultMap, rsw, cacheKey, nestedResultMap.getConstructorResultMappings(),
          prependPrefix(resultMapping.getColumnPrefix(), columnPrefix));
    } else if (resultMapping.getNestedQueryId() == null) {
      final String column = prependPrefix(resultMapping.getColumn(), columnPrefix);
      final TypeHandler<?> th = resultMapping.getTypeHandler();
      List<String> mappedColumnNames = rsw.getMappedColumnNames(resultMap, columnPrefix);
      // Issue #114
      if (column != null && mappedColumnNames.contains(column.toUpperCase(Locale.ENGLISH))) {
        final Object value = th.getResult(rsw.getResultSet(), column);
        if (value != null) {
          cacheKey.update(column);
          cacheKey.update(value);
        }
      }
    }
  }
}
 
Example #13
Source File: XmlConfigBuilderTest.java    From mybaties with Apache License 2.0 6 votes vote down vote up
@Test
public void registerJavaTypeInitializingTypeHandler() {
  final String MAPPER_CONFIG = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
      + "<!DOCTYPE configuration PUBLIC \"-//mybatis.org//DTD Config 3.0//EN\" \"http://mybatis.org/dtd/mybatis-3-config.dtd\">\n" 
      + "<configuration>\n" 
      + "  <typeHandlers>\n"
      + "    <typeHandler javaType=\"org.apache.ibatis.builder.XmlConfigBuilderTest$MyEnum\"\n"
      + "      handler=\"org.apache.ibatis.builder.XmlConfigBuilderTest$EnumOrderTypeHandler\"/>\n" 
      + "  </typeHandlers>\n" 
      + "</configuration>\n";

  XMLConfigBuilder builder = new XMLConfigBuilder(new StringReader(MAPPER_CONFIG));
  builder.parse();

  TypeHandlerRegistry typeHandlerRegistry = builder.getConfiguration().getTypeHandlerRegistry();
  TypeHandler<MyEnum> typeHandler = typeHandlerRegistry.getTypeHandler(MyEnum.class);

  assertTrue(typeHandler instanceof EnumOrderTypeHandler);
  assertArrayEquals(MyEnum.values(), ((EnumOrderTypeHandler) typeHandler).constants);
}
 
Example #14
Source File: DefaultResultSetHandler.java    From mybaties with Apache License 2.0 6 votes vote down vote up
private Object createParameterizedResultObject(ResultSetWrapper rsw, Class<?> resultType, List<ResultMapping> constructorMappings,
    List<Class<?>> constructorArgTypes, List<Object> constructorArgs, String columnPrefix) throws SQLException {
  boolean foundValues = false;
  for (ResultMapping constructorMapping : constructorMappings) {
    final Class<?> parameterType = constructorMapping.getJavaType();
    final String column = constructorMapping.getColumn();
    final Object value;
    if (constructorMapping.getNestedQueryId() != null) {
      value = getNestedQueryConstructorValue(rsw.getResultSet(), constructorMapping, columnPrefix);
    } else if (constructorMapping.getNestedResultMapId() != null) {
      final ResultMap resultMap = configuration.getResultMap(constructorMapping.getNestedResultMapId());
      value = getRowValue(rsw, resultMap);
    } else {
      final TypeHandler<?> typeHandler = constructorMapping.getTypeHandler();
      value = typeHandler.getResult(rsw.getResultSet(), prependPrefix(column, columnPrefix));
    }
    constructorArgTypes.add(parameterType);
    constructorArgs.add(value);
    foundValues = value != null || foundValues;
  }
  return foundValues ? objectFactory.create(resultType, constructorArgTypes, constructorArgs) : null;
}
 
Example #15
Source File: XMLMapperBuilder.java    From mybatis with Apache License 2.0 6 votes vote down vote up
private Discriminator processDiscriminatorElement(XNode context, Class<?> resultType, List<ResultMapping> resultMappings) throws Exception {
  String column = context.getStringAttribute("column");
  String javaType = context.getStringAttribute("javaType");
  String jdbcType = context.getStringAttribute("jdbcType");
  String typeHandler = context.getStringAttribute("typeHandler");
  Class<?> javaTypeClass = resolveClass(javaType);
  @SuppressWarnings("unchecked")
  Class<? extends TypeHandler<?>> typeHandlerClass = (Class<? extends TypeHandler<?>>) resolveClass(typeHandler);
  JdbcType jdbcTypeEnum = resolveJdbcType(jdbcType);
  Map<String, String> discriminatorMap = new HashMap<String, String>();
  for (XNode caseChild : context.getChildren()) {
    String value = caseChild.getStringAttribute("value");
    String resultMap = caseChild.getStringAttribute("resultMap", processNestedResultMappings(caseChild, resultMappings));
    discriminatorMap.put(value, resultMap);
  }
  return builderAssistant.buildDiscriminator(resultType, column, javaTypeClass, jdbcTypeEnum, typeHandlerClass, discriminatorMap);
}
 
Example #16
Source File: MybatisPersistentPropertyImpl.java    From spring-data-mybatis with Apache License 2.0 6 votes vote down vote up
@Override
public Class<? extends TypeHandler<?>> getSpecifiedTypeHandler() {
	if (isAnnotationPresent(
			org.springframework.data.mybatis.annotation.TypeHandler.class)) {
		String value = getRequiredAnnotation(
				org.springframework.data.mybatis.annotation.TypeHandler.class)
						.value();
		try {
			Class<?> clz = ClassUtils.forName(value,
					ClassUtils.getDefaultClassLoader());

			if (!TypeHandler.class.isAssignableFrom(clz)) {
				throw new MappingException("The specified type handler with value: "
						+ value
						+ " must implement from org.apache.ibatis.type.TypeHandler");
			}
			return (Class<? extends TypeHandler<?>>) clz;
		}
		catch (ClassNotFoundException e) {
			throw new MappingException("The specified type handler with value: "
					+ value + " not found.");
		}
	}
	return null;
}
 
Example #17
Source File: DefaultResultSetHandler.java    From mybaties with Apache License 2.0 6 votes vote down vote up
private Object prepareCompositeKeyParameter(ResultSet rs, ResultMapping resultMapping, Class<?> parameterType, String columnPrefix) throws SQLException {
  final Object parameterObject = instantiateParameterObject(parameterType);
  final MetaObject metaObject = configuration.newMetaObject(parameterObject);
  boolean foundValues = false;
  for (ResultMapping innerResultMapping : resultMapping.getComposites()) {
    final Class<?> propType = metaObject.getSetterType(innerResultMapping.getProperty());
    final TypeHandler<?> typeHandler = typeHandlerRegistry.getTypeHandler(propType);
    final Object propValue = typeHandler.getResult(rs, prependPrefix(innerResultMapping.getColumn(), columnPrefix));
    // issue #353 & #560 do not execute nested query if key is null
    if (propValue != null) {
      metaObject.setValue(innerResultMapping.getProperty(), propValue);
      foundValues = true;
    }
  }
  return foundValues ? parameterObject : null;
}
 
Example #18
Source File: XMLMapperBuilder.java    From mybatis with 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 File: DefaultResultSetHandler.java    From mybaties with 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 #20
Source File: DefaultResultSetHandler.java    From mybatis with Apache License 2.0 6 votes vote down vote up
private Object getPropertyMappingValue(ResultSet rs, MetaObject metaResultObject, ResultMapping propertyMapping, ResultLoaderMap lazyLoader, String columnPrefix)
    throws SQLException {
  if (propertyMapping.getNestedQueryId() != null) {
    return getNestedQueryMappingValue(rs, metaResultObject, propertyMapping, lazyLoader, columnPrefix);
  } else if (propertyMapping.getResultSet() != null) {
    addPendingChildRelation(rs, metaResultObject, propertyMapping);
    return NO_VALUE;
  } else if (propertyMapping.getNestedResultMapId() != null) {
    // the user added a column attribute to a nested result map, ignore it
    return NO_VALUE;
  } else {
    final TypeHandler<?> typeHandler = propertyMapping.getTypeHandler();
    final String column = prependPrefix(propertyMapping.getColumn(), columnPrefix);
    return typeHandler.getResult(rs, column);
  }
}
 
Example #21
Source File: DefaultResultSetHandler.java    From mybatis with 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 #22
Source File: DefaultResultSetHandler.java    From mybaties with Apache License 2.0 5 votes vote down vote up
private boolean applyAutomaticMappings(ResultSetWrapper rsw, ResultMap resultMap, MetaObject metaObject, String columnPrefix) throws SQLException {
  final List<String> unmappedColumnNames = rsw.getUnmappedColumnNames(resultMap, columnPrefix);
  boolean foundValues = false;
  for (String columnName : unmappedColumnNames) {
    String propertyName = columnName;
    if (columnPrefix != null && !columnPrefix.isEmpty()) {
      // When columnPrefix is specified,
      // ignore columns without the prefix.
      if (columnName.toUpperCase(Locale.ENGLISH).startsWith(columnPrefix)) {
        propertyName = columnName.substring(columnPrefix.length());
      } else {
        continue;
      }
    }
    final String property = metaObject.findProperty(propertyName, configuration.isMapUnderscoreToCamelCase());
    if (property != null && metaObject.hasSetter(property)) {
      final Class<?> propertyType = metaObject.getSetterType(property);
      if (typeHandlerRegistry.hasTypeHandler(propertyType)) {
        final TypeHandler<?> typeHandler = rsw.getTypeHandler(propertyType, columnName);
        //巧妙的用TypeHandler取得结果
        final Object value = typeHandler.getResult(rsw.getResultSet(), columnName);
        // issue #377, call setter on nulls
        if (value != null || configuration.isCallSettersOnNulls()) {
          if (value != null || !propertyType.isPrimitive()) {
            //然后巧妙的用反射来设置到对象
            metaObject.setValue(property, value);
          }
          foundValues = true;
        }
      }
    }
  }
  return foundValues;
}
 
Example #23
Source File: MapperBuilderAssistant.java    From mybaties with Apache License 2.0 5 votes vote down vote up
public Discriminator buildDiscriminator(
    Class<?> resultType,
    String column,
    Class<?> javaType,
    JdbcType jdbcType,
    Class<? extends TypeHandler<?>> typeHandler,
    Map<String, String> discriminatorMap) {
  ResultMapping resultMapping = buildResultMapping(
      resultType,
      null,
      column,
      javaType,
      jdbcType,
      null,
      null,
      null,
      null,
      typeHandler,
      new ArrayList<ResultFlag>(),
      null,
      null,
      false);
  Map<String, String> namespaceDiscriminatorMap = new HashMap<String, String>();
  for (Map.Entry<String, String> e : discriminatorMap.entrySet()) {
    String resultMap = e.getValue();
    resultMap = applyCurrentNamespace(resultMap, true);
    namespaceDiscriminatorMap.put(e.getKey(), resultMap);
  }
  Discriminator.Builder discriminatorBuilder = new Discriminator.Builder(configuration, resultMapping, namespaceDiscriminatorMap);
  return discriminatorBuilder.build();
}
 
Example #24
Source File: DefaultResultSetHandler.java    From mybaties with Apache License 2.0 5 votes vote down vote up
private Object getPropertyMappingValue(ResultSet rs, MetaObject metaResultObject, ResultMapping propertyMapping, ResultLoaderMap lazyLoader, String columnPrefix)
    throws SQLException {
  if (propertyMapping.getNestedQueryId() != null) {
    return getNestedQueryMappingValue(rs, metaResultObject, propertyMapping, lazyLoader, columnPrefix);
  } else if (propertyMapping.getResultSet() != null) {
    addPendingChildRelation(rs, metaResultObject, propertyMapping);   // TODO is that OK?
    return DEFERED;
  } else {
    final TypeHandler<?> typeHandler = propertyMapping.getTypeHandler();
    final String column = prependPrefix(propertyMapping.getColumn(), columnPrefix);
    return typeHandler.getResult(rs, column);
  }
}
 
Example #25
Source File: DefaultParameterHandler.java    From mybaties with Apache License 2.0 5 votes vote down vote up
@Override
public void setParameters(PreparedStatement ps) throws SQLException {
  ErrorContext.instance().activity("setting parameters").object(mappedStatement.getParameterMap().getId());
  List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
  if (parameterMappings != null) {
    //循环设参数
    for (int i = 0; i < parameterMappings.size(); i++) {
      ParameterMapping parameterMapping = parameterMappings.get(i);
      if (parameterMapping.getMode() != ParameterMode.OUT) {
        //如果不是OUT,才设进去
        Object value;
        String propertyName = parameterMapping.getProperty();
        if (boundSql.hasAdditionalParameter(propertyName)) { // issue #448 ask first for additional params
          //若有额外的参数, 设为额外的参数
          value = boundSql.getAdditionalParameter(propertyName);
        } else if (parameterObject == null) {
          //若参数为null,直接设null
          value = null;
        } else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
          //若参数有相应的TypeHandler,直接设object
          value = parameterObject;
        } else {
          //除此以外,MetaObject.getValue反射取得值设进去
          MetaObject metaObject = configuration.newMetaObject(parameterObject);
          value = metaObject.getValue(propertyName);
        }
        TypeHandler typeHandler = parameterMapping.getTypeHandler();
        JdbcType jdbcType = parameterMapping.getJdbcType();
        if (value == null && jdbcType == null) {
          //不同类型的set方法不同,所以委派给子类的setParameter方法
          jdbcType = configuration.getJdbcTypeForNull();
        }
        typeHandler.setParameter(ps, i + 1, value, jdbcType);
      }
    }
  }
}
 
Example #26
Source File: BaseBuilder.java    From mybaties with Apache License 2.0 5 votes vote down vote up
protected TypeHandler<?> resolveTypeHandler(Class<?> javaType, Class<? extends TypeHandler<?>> typeHandlerType) {
  if (typeHandlerType == null) {
    return null;
  }
  // javaType ignored for injected handlers see issue #746 for full detail
  //去typeHandlerRegistry查询对应的TypeHandler
  TypeHandler<?> handler = typeHandlerRegistry.getMappingTypeHandler(typeHandlerType);
  if (handler == null) {
    // not in registry, create a new one
      //如果没有在Registry找到,调用typeHandlerRegistry.getInstance来new一个TypeHandler返回
    handler = typeHandlerRegistry.getInstance(javaType, typeHandlerType);
  }
  return handler;
}
 
Example #27
Source File: Jdbc3KeyGenerator.java    From mybatis with Apache License 2.0 5 votes vote down vote up
private void populateKeys(ResultSet rs, MetaObject metaParam, String[] keyProperties, TypeHandler<?>[] typeHandlers) throws SQLException {
  for (int i = 0; i < keyProperties.length; i++) {
    TypeHandler<?> th = typeHandlers[i];
    if (th != null) {
      Object value = th.getResult(rs, i + 1);
      metaParam.setValue(keyProperties[i], value);
    }
  }
}
 
Example #28
Source File: DefaultResultSetHandler.java    From mybatis with Apache License 2.0 5 votes vote down vote up
private boolean applyAutomaticMappings(ResultSetWrapper rsw, ResultMap resultMap, MetaObject metaObject, String columnPrefix) throws SQLException {
  final List<String> unmappedColumnNames = rsw.getUnmappedColumnNames(resultMap, columnPrefix);
  boolean foundValues = false;
  for (String columnName : unmappedColumnNames) {
    String propertyName = columnName;
    if (columnPrefix != null && !columnPrefix.isEmpty()) {
      // When columnPrefix is specified,
      // ignore columns without the prefix.
      if (columnName.toUpperCase(Locale.ENGLISH).startsWith(columnPrefix)) {
        propertyName = columnName.substring(columnPrefix.length());
      } else {
        continue;
      }
    }
    final String property = metaObject.findProperty(propertyName, configuration.isMapUnderscoreToCamelCase());
    if (property != null && metaObject.hasSetter(property)) {
      final Class<?> propertyType = metaObject.getSetterType(property);
      if (typeHandlerRegistry.hasTypeHandler(propertyType)) {
        final TypeHandler<?> typeHandler = rsw.getTypeHandler(propertyType, columnName);
        //巧妙的用TypeHandler取得结果
        final Object value = typeHandler.getResult(rsw.getResultSet(), columnName);
        // issue #377, call setter on nulls
        if (value != null || configuration.isCallSettersOnNulls()) {
          if (value != null || !propertyType.isPrimitive()) {
            //然后巧妙的用反射来设置到对象
            metaObject.setValue(property, value);
          }
          foundValues = true;
        }
      }
    }
  }
  return foundValues;
}
 
Example #29
Source File: MyBatisDataStore.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Prepare the {@link TypeHandler} for use with this datastore.
 */
private TypeHandlerRegistry prepare(final TypeHandler<?> handler) {
  if (handler instanceof CipherAwareTypeHandler<?>) {
    ((CipherAwareTypeHandler<?>) handler).setCipher(databaseCipher);
  }
  if (sensitiveAttributeFilter != null && handler instanceof AbstractJsonTypeHandler<?>) {
    ((AbstractJsonTypeHandler<?>) handler).encryptSensitiveFields(passwordHelper, sensitiveAttributeFilter);
  }
  Configuration mybatisConfig = sessionFactory.getConfiguration();
  registerSimpleAlias(mybatisConfig.getTypeAliasRegistry(), handler.getClass());
  return mybatisConfig.getTypeHandlerRegistry();
}
 
Example #30
Source File: BaseBuilder.java    From mybatis with Apache License 2.0 5 votes vote down vote up
protected TypeHandler<?> resolveTypeHandler(Class<?> javaType, Class<? extends TypeHandler<?>> typeHandlerType) {
  if (typeHandlerType == null) {
    return null;
  }
  // javaType ignored for injected handlers see issue #746 for full detail
  //去typeHandlerRegistry查询对应的TypeHandler
  TypeHandler<?> handler = typeHandlerRegistry.getMappingTypeHandler(typeHandlerType);
  if (handler == null) {
    // not in registry, create a new one
      //如果没有在Registry找到,调用typeHandlerRegistry.getInstance来new一个TypeHandler返回
    handler = typeHandlerRegistry.getInstance(javaType, typeHandlerType);
  }
  return handler;
}