Java Code Examples for org.apache.ibatis.type.TypeHandler

The following examples show how to use org.apache.ibatis.type.TypeHandler. 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: XmlConfigBuilderTest.java    License: 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 2
Source Project: mybatis   Source File: DefaultResultSetHandler.java    License: 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 3
Source Project: mybatis   Source File: DefaultResultSetHandler.java    License: 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 4
Source Project: mybatis   Source File: DefaultResultSetHandler.java    License: 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 5
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 6
Source Project: mybatis   Source File: XMLMapperBuilder.java    License: 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 7
@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 8
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 9
Source Project: mybatis   Source File: DefaultResultSetHandler.java    License: 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 10
Source Project: mybatis   Source File: MapperBuilderAssistant.java    License: 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 11
Source Project: mybaties   Source File: SqlRunner.java    License: 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 12
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 13
Source Project: mybatis   Source File: SqlRunner.java    License: 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 14
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 15
Source Project: mybatis   Source File: MapperAnnotationBuilder.java    License: 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 16
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 17
Source Project: mybaties   Source File: DefaultResultSetHandler.java    License: 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 18
Source Project: mybaties   Source File: DefaultResultSetHandler.java    License: 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 19
Source Project: mybaties   Source File: DefaultResultSetHandler.java    License: 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 20
Source Project: mybaties   Source File: DefaultResultSetHandler.java    License: 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 21
Source Project: mybaties   Source File: XmlConfigBuilderTest.java    License: 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 22
public DemoDatabaseAutoConfiguration(MybatisPlusProperties properties,
                                     DatabaseProperties databaseProperties,
                                     ObjectProvider<Interceptor[]> interceptorsProvider,
                                     ObjectProvider<TypeHandler[]> typeHandlersProvider,
                                     ObjectProvider<LanguageDriver[]> languageDriversProvider,
                                     ResourceLoader resourceLoader,
                                     ObjectProvider<DatabaseIdProvider> databaseIdProvider,
                                     ObjectProvider<List<ConfigurationCustomizer>> configurationCustomizersProvider,
                                     ObjectProvider<List<MybatisPlusPropertiesCustomizer>> mybatisPlusPropertiesCustomizerProvider,
                                     ApplicationContext applicationContext) {
    super(properties, databaseProperties, interceptorsProvider, typeHandlersProvider,
            languageDriversProvider, resourceLoader, databaseIdProvider,
            configurationCustomizersProvider, mybatisPlusPropertiesCustomizerProvider, applicationContext);
    log.debug("检测到 zuihou.database.multiTenantType!=DATASOURCE,启用了 AuthorityDatabaseAutoConfiguration");
}
 
Example 23
public FileDatabaseAutoConfiguration(MybatisPlusProperties properties,
                                     DatabaseProperties databaseProperties,
                                     ObjectProvider<Interceptor[]> interceptorsProvider,
                                     ObjectProvider<TypeHandler[]> typeHandlersProvider,
                                     ObjectProvider<LanguageDriver[]> languageDriversProvider,
                                     ResourceLoader resourceLoader,
                                     ObjectProvider<DatabaseIdProvider> databaseIdProvider,
                                     ObjectProvider<List<ConfigurationCustomizer>> configurationCustomizersProvider,
                                     ObjectProvider<List<MybatisPlusPropertiesCustomizer>> mybatisPlusPropertiesCustomizerProvider,
                                     ApplicationContext applicationContext) {
    super(properties, databaseProperties, interceptorsProvider, typeHandlersProvider,
            languageDriversProvider, resourceLoader, databaseIdProvider,
            configurationCustomizersProvider, mybatisPlusPropertiesCustomizerProvider, applicationContext);
}
 
Example 24
public AuthorityDatabaseAutoConfiguration(MybatisPlusProperties properties,
                                          DatabaseProperties databaseProperties,
                                          ObjectProvider<Interceptor[]> interceptorsProvider,
                                          ObjectProvider<TypeHandler[]> typeHandlersProvider,
                                          ObjectProvider<LanguageDriver[]> languageDriversProvider,
                                          ResourceLoader resourceLoader,
                                          ObjectProvider<DatabaseIdProvider> databaseIdProvider,
                                          ObjectProvider<List<ConfigurationCustomizer>> configurationCustomizersProvider,
                                          ObjectProvider<List<MybatisPlusPropertiesCustomizer>> mybatisPlusPropertiesCustomizerProvider,
                                          ApplicationContext applicationContext) {
    super(properties, databaseProperties, interceptorsProvider, typeHandlersProvider,
            languageDriversProvider, resourceLoader, databaseIdProvider,
            configurationCustomizersProvider, mybatisPlusPropertiesCustomizerProvider, applicationContext);
    log.debug("检测到 zuihou.database.multiTenantType!=DATASOURCE,加载了 AuthorityDatabaseAutoConfiguration");
}
 
Example 25
public OrderDatabaseAutoConfiguration(MybatisPlusProperties properties,
                                      DatabaseProperties databaseProperties,
                                      ObjectProvider<Interceptor[]> interceptorsProvider,
                                      ObjectProvider<TypeHandler[]> typeHandlersProvider,
                                      ObjectProvider<LanguageDriver[]> languageDriversProvider,
                                      ResourceLoader resourceLoader,
                                      ObjectProvider<DatabaseIdProvider> databaseIdProvider,
                                      ObjectProvider<List<ConfigurationCustomizer>> configurationCustomizersProvider,
                                      ObjectProvider<List<MybatisPlusPropertiesCustomizer>> mybatisPlusPropertiesCustomizerProvider,
                                      ApplicationContext applicationContext) {
    super(properties, databaseProperties, interceptorsProvider, typeHandlersProvider,
            languageDriversProvider, resourceLoader, databaseIdProvider,
            configurationCustomizersProvider, mybatisPlusPropertiesCustomizerProvider, applicationContext);
    log.debug("检测到 zuihou.database.multiTenantType!=DATASOURCE,启用了 AuthorityDatabaseAutoConfiguration");
}
 
Example 26
public JobsDatabaseAutoConfiguration(MybatisPlusProperties properties,
                                     DatabaseProperties databaseProperties,
                                     ObjectProvider<Interceptor[]> interceptorsProvider,
                                     ObjectProvider<TypeHandler[]> typeHandlersProvider,
                                     ObjectProvider<LanguageDriver[]> languageDriversProvider,
                                     ResourceLoader resourceLoader,
                                     ObjectProvider<DatabaseIdProvider> databaseIdProvider,
                                     ObjectProvider<List<ConfigurationCustomizer>> configurationCustomizersProvider,
                                     ObjectProvider<List<MybatisPlusPropertiesCustomizer>> mybatisPlusPropertiesCustomizerProvider,
                                     ApplicationContext applicationContext) {
    super(properties, databaseProperties, interceptorsProvider, typeHandlersProvider,
            languageDriversProvider, resourceLoader, databaseIdProvider,
            configurationCustomizersProvider, mybatisPlusPropertiesCustomizerProvider, applicationContext);
    log.debug("检测到 zuihou.database.multiTenantType!=DATASOURCE,加载了 AuthorityDatabaseAutoConfiguration");
}
 
Example 27
public MsgsDatabaseAutoConfiguration(MybatisPlusProperties properties,
                                     DatabaseProperties databaseProperties,
                                     ObjectProvider<Interceptor[]> interceptorsProvider,
                                     ObjectProvider<TypeHandler[]> typeHandlersProvider,
                                     ObjectProvider<LanguageDriver[]> languageDriversProvider,
                                     ResourceLoader resourceLoader,
                                     ObjectProvider<DatabaseIdProvider> databaseIdProvider,
                                     ObjectProvider<List<ConfigurationCustomizer>> configurationCustomizersProvider,
                                     ObjectProvider<List<MybatisPlusPropertiesCustomizer>> mybatisPlusPropertiesCustomizerProvider,
                                     ApplicationContext applicationContext) {
    super(properties, databaseProperties, interceptorsProvider, typeHandlersProvider,
            languageDriversProvider, resourceLoader, databaseIdProvider,
            configurationCustomizersProvider, mybatisPlusPropertiesCustomizerProvider, applicationContext);
    log.debug("检测到 zuihou.database.multiTenantType!=DATASOURCE,启用了 AuthorityDatabaseAutoConfiguration");
}
 
Example 28
Source Project: tk-mybatis   Source File: MultipleJdbc3KeyGenerator.java    License: MIT License 5 votes vote down vote up
private TypeHandler<?>[] getTypeHandlers(TypeHandlerRegistry typeHandlerRegistry, MetaObject metaParam, String[] keyProperties) {
    TypeHandler<?>[] typeHandlers = new TypeHandler<?>[keyProperties.length];
    for (int i = 0; i < keyProperties.length; i++) {
        if (metaParam.hasSetter(keyProperties[i])) {
            Class<?> keyPropertyType = metaParam.getSetterType(keyProperties[i]);
            TypeHandler<?> th = typeHandlerRegistry.getTypeHandler(keyPropertyType);
            typeHandlers[i] = th;
        }
    }
    return typeHandlers;
}
 
Example 29
Source Project: tk-mybatis   Source File: MultipleJdbc3KeyGenerator.java    License: MIT License 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 30
Source Project: mybatis   Source File: ResultSetWrapper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Gets the type handler to use when reading the result set.
 * Tries to get from the TypeHandlerRegistry by searching for the property type.
 * If not found it gets the column JDBC type and tries to get a handler for it.
 * 
 * @param propertyType
 * @param columnName
 * @return
 */
public TypeHandler<?> getTypeHandler(Class<?> propertyType, String columnName) {
  TypeHandler<?> handler = null;
  Map<Class<?>, TypeHandler<?>> columnHandlers = typeHandlerMap.get(columnName);
  if (columnHandlers == null) {
    columnHandlers = new HashMap<Class<?>, TypeHandler<?>>();
    typeHandlerMap.put(columnName, columnHandlers);
  } else {
    handler = columnHandlers.get(propertyType);
  }
  if (handler == null) {
    handler = typeHandlerRegistry.getTypeHandler(propertyType);
    // Replicate logic of UnknownTypeHandler#resolveTypeHandler
    // See issue #59 comment 10
    if (handler == null || handler instanceof UnknownTypeHandler) {
      final int index = columnNames.indexOf(columnName);
      final JdbcType jdbcType = jdbcTypes.get(index);
      final Class<?> javaType = resolveClass(classNames.get(index));
      if (javaType != null && jdbcType != null) {
        handler = typeHandlerRegistry.getTypeHandler(javaType, jdbcType);
      } else if (javaType != null) {
        handler = typeHandlerRegistry.getTypeHandler(javaType);
      } else if (jdbcType != null) {
        handler = typeHandlerRegistry.getTypeHandler(jdbcType);
      }
    }
    if (handler == null || handler instanceof UnknownTypeHandler) {
      handler = new ObjectTypeHandler();
    }
    columnHandlers.put(propertyType, handler);
  }
  return handler;
}