org.apache.ibatis.mapping.ResultMap Java Examples

The following examples show how to use org.apache.ibatis.mapping.ResultMap. 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: XMLMapperBuilder.java    From mybaties with Apache License 2.0 7 votes vote down vote up
private String processNestedResultMappings(XNode context, List<ResultMapping> resultMappings) throws Exception {
	  //处理association|collection|case
    if ("association".equals(context.getName())
        || "collection".equals(context.getName())
        || "case".equals(context.getName())) {
    	
//    	<resultMap id="blogResult" type="Blog">
//    	  <association property="author" column="author_id" javaType="Author" select="selectAuthor"/>
//    	</resultMap>
//如果不是嵌套查询
      if (context.getStringAttribute("select") == null) {
    	//则递归调用5.1 resultMapElement
        ResultMap resultMap = resultMapElement(context, resultMappings);
        return resultMap.getId();
      }
    }
    return null;
  }
 
Example #2
Source File: XMLMapperBuilder.java    From mybatis with Apache License 2.0 6 votes vote down vote up
private String processNestedResultMappings(XNode context, List<ResultMapping> resultMappings) throws Exception {
	  //处理association|collection|case
    if ("association".equals(context.getName())
        || "collection".equals(context.getName())
        || "case".equals(context.getName())) {
    	
//    	<resultMap id="blogResult" type="Blog">
//    	  <association property="author" column="author_id" javaType="Author" select="selectAuthor"/>
//    	</resultMap>
//如果不是嵌套查询
      if (context.getStringAttribute("select") == null) {
    	//则递归调用5.1 resultMapElement
        ResultMap resultMap = resultMapElement(context, resultMappings);
        return resultMap.getId();
      }
    }
    return null;
  }
 
Example #3
Source File: DefaultResultSetHandler.java    From mybaties with Apache License 2.0 6 votes vote down vote up
public ResultMap resolveDiscriminatedResultMap(ResultSet rs, ResultMap resultMap, String columnPrefix) throws SQLException {
  Set<String> pastDiscriminators = new HashSet<String>();
  Discriminator discriminator = resultMap.getDiscriminator();
  while (discriminator != null) {
    final Object value = getDiscriminatorValue(rs, discriminator, columnPrefix);
    final String discriminatedMapId = discriminator.getMapIdFor(String.valueOf(value));
    if (configuration.hasResultMap(discriminatedMapId)) {
      resultMap = configuration.getResultMap(discriminatedMapId);
      Discriminator lastDiscriminator = discriminator;
      discriminator = resultMap.getDiscriminator();
      if (discriminator == lastDiscriminator || !pastDiscriminators.add(discriminatedMapId)) {
        break;
      }
    } else {
      break;
    }
  }
  return resultMap;
}
 
Example #4
Source File: DefaultResultSetHandler.java    From mybatis with Apache License 2.0 6 votes vote down vote up
private void handleResultSet(ResultSetWrapper rsw, ResultMap resultMap, List<Object> multipleResults, ResultMapping parentMapping) throws SQLException {
  try {
    if (parentMapping != null) {
      handleRowValues(rsw, resultMap, null, RowBounds.DEFAULT, parentMapping);
    } else {
      if (resultHandler == null) {
        //如果没有resultHandler
        //新建DefaultResultHandler
        DefaultResultHandler defaultResultHandler = new DefaultResultHandler(objectFactory);
        //调用自己的handleRowValues
        handleRowValues(rsw, resultMap, defaultResultHandler, rowBounds, null);
        //得到记录的list
        multipleResults.add(defaultResultHandler.getResultList());
      } else {
        //如果有resultHandler
        handleRowValues(rsw, resultMap, resultHandler, rowBounds, null);
      }
    }
  } finally {
    //最后别忘了关闭结果集,这个居然出bug了
    // issue #228 (close resultsets)
    closeResultSet(rsw.getResultSet());
  }
}
 
Example #5
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 #6
Source File: CustomHandlerInterceptor.java    From BlogManagePlatform with Apache License 2.0 6 votes vote down vote up
private static CustomHandler resolveNew(String id, Method method, MappedStatement ms, CustomResultHandler annotation) {
	Class<? extends CustomHandler> instanceClass = annotation.value();
	//每次都必须是一个新对象
	CustomHandler instance = ReflectUtil.instance(instanceClass);
	List<ResultMap> resultMaps = ms.getResultMaps();
	if (!instance.support(resultMaps)) {
		//如果不支持
		noCustomes.add(id);
		String string = resultMaps.stream().map((item) -> item.getType().getCanonicalName()).collect(Collectors.joining(","));
		log.warn("{}方法的返回值类型{}不被{}所支持,将不会使用该CustomHandler", id, string, instanceClass.getCanonicalName());
		return null;
	}
	cache.put(id, instanceClass);
	//在需要返回结果的情况下,需要记录下返回值类型
	CustomHandlerContext context = instance.resolveContext(method, ms.getConfiguration());
	contextCache.put(id, context);
	instance.setContext(context);
	return instance;
}
 
Example #7
Source File: DefaultResultSetHandler.java    From mybaties with Apache License 2.0 6 votes vote down vote up
private Object createResultObject(ResultSetWrapper rsw, ResultMap resultMap, ResultLoaderMap lazyLoader, String columnPrefix) throws SQLException {
  final List<Class<?>> constructorArgTypes = new ArrayList<Class<?>>();
  final List<Object> constructorArgs = new ArrayList<Object>();
  final Object resultObject = createResultObject(rsw, resultMap, constructorArgTypes, constructorArgs, columnPrefix);
  if (resultObject != null && !typeHandlerRegistry.hasTypeHandler(resultMap.getType())) {
    final List<ResultMapping> propertyMappings = resultMap.getPropertyResultMappings();
    for (ResultMapping propertyMapping : propertyMappings) {
      // issue gcode #109 && issue #149
      if (propertyMapping.getNestedQueryId() != null && propertyMapping.isLazy()) {
        //TODO 使用代理(cglib/javaassist)
        return configuration.getProxyFactory().createProxy(resultObject, lazyLoader, configuration, objectFactory, constructorArgTypes, constructorArgs);
      }
    }
  }
  return resultObject;
}
 
Example #8
Source File: DefaultResultSetHandler.java    From mybaties with Apache License 2.0 6 votes vote down vote up
private Object createResultObject(ResultSetWrapper rsw, ResultMap resultMap, List<Class<?>> constructorArgTypes, List<Object> constructorArgs, String columnPrefix)
     throws SQLException {
//得到result type
   final Class<?> resultType = resultMap.getType();
   final MetaClass metaType = MetaClass.forClass(resultType);
   final List<ResultMapping> constructorMappings = resultMap.getConstructorResultMappings();
   if (typeHandlerRegistry.hasTypeHandler(resultType)) {
     //基本型
     return createPrimitiveResultObject(rsw, resultMap, columnPrefix);
   } else if (!constructorMappings.isEmpty()) {
     //有参数的构造函数
     return createParameterizedResultObject(rsw, resultType, constructorMappings, constructorArgTypes, constructorArgs, columnPrefix);
   } else if (resultType.isInterface() || metaType.hasDefaultConstructor()) {
     //普通bean类型
     return objectFactory.create(resultType);
   } else if (shouldApplyAutomaticMappings(resultMap, false)) {
     //自动映射
     return createByConstructorSignature(rsw, resultType, constructorArgTypes, constructorArgs, columnPrefix);
   }
   throw new ExecutorException("Do not know how to create an instance of " + resultType);
 }
 
Example #9
Source File: DefaultResultSetHandler.java    From mybatis with Apache License 2.0 6 votes vote down vote up
private boolean applyPropertyMappings(ResultSetWrapper rsw, ResultMap resultMap, MetaObject metaObject, ResultLoaderMap lazyLoader, String columnPrefix)
    throws SQLException {
  final List<String> mappedColumnNames = rsw.getMappedColumnNames(resultMap, columnPrefix);
  boolean foundValues = false;
  final List<ResultMapping> propertyMappings = resultMap.getPropertyResultMappings();
  for (ResultMapping propertyMapping : propertyMappings) {
    final String column = prependPrefix(propertyMapping.getColumn(), columnPrefix);
    if (propertyMapping.isCompositeResult() 
        || (column != null && mappedColumnNames.contains(column.toUpperCase(Locale.ENGLISH))) 
        || propertyMapping.getResultSet() != null) {
      Object value = getPropertyMappingValue(rsw.getResultSet(), metaObject, propertyMapping, lazyLoader, columnPrefix);
      // issue #541 make property optional
      final String property = propertyMapping.getProperty();
      // issue #377, call setter on nulls
      if (value != NO_VALUE && property != null && (value != null || configuration.isCallSettersOnNulls())) {
        if (value != null || !metaObject.getSetterType(property).isPrimitive()) {
          metaObject.setValue(property, value);
        }
        foundValues = true;
      }
    }
  }
  return foundValues;
}
 
Example #10
Source File: DefaultResultSetHandler.java    From mybatis with Apache License 2.0 6 votes vote down vote up
private Object getRowValue(ResultSetWrapper rsw, ResultMap resultMap) throws SQLException {
  //实例化ResultLoaderMap(延迟加载器)
  final ResultLoaderMap lazyLoader = new ResultLoaderMap();
  //调用自己的createResultObject,内部就是new一个对象(如果是简单类型,new完也把值赋进去)
  Object resultObject = createResultObject(rsw, resultMap, lazyLoader, null);
  if (resultObject != null && !typeHandlerRegistry.hasTypeHandler(resultMap.getType())) {
    //一般不是简单类型不会有typehandler,这个if会进来
    final MetaObject metaObject = configuration.newMetaObject(resultObject);
    boolean foundValues = !resultMap.getConstructorResultMappings().isEmpty();
    if (shouldApplyAutomaticMappings(resultMap, false)) {        
      //自动映射咯
      //这里把每个列的值都赋到相应的字段里去了
  	foundValues = applyAutomaticMappings(rsw, resultMap, metaObject, null) || foundValues;
    }
    foundValues = applyPropertyMappings(rsw, resultMap, metaObject, lazyLoader, null) || foundValues;
    foundValues = lazyLoader.size() > 0 || foundValues;
    resultObject = foundValues ? resultObject : null;
    return resultObject;
  }
  return resultObject;
}
 
Example #11
Source File: DefaultResultSetHandler.java    From mybaties with Apache License 2.0 6 votes vote down vote up
private void handleResultSet(ResultSetWrapper rsw, ResultMap resultMap, List<Object> multipleResults, ResultMapping parentMapping) throws SQLException {
  try {
    if (parentMapping != null) {
      handleRowValues(rsw, resultMap, null, RowBounds.DEFAULT, parentMapping);
    } else {
      if (resultHandler == null) {
        //如果没有resultHandler
        //新建DefaultResultHandler
        DefaultResultHandler defaultResultHandler = new DefaultResultHandler(objectFactory);
        //调用自己的handleRowValues
        handleRowValues(rsw, resultMap, defaultResultHandler, rowBounds, null);
        //得到记录的list
        multipleResults.add(defaultResultHandler.getResultList());
      } else {
        //如果有resultHandler
        handleRowValues(rsw, resultMap, resultHandler, rowBounds, null);
      }
    }
  } finally {
    //最后别忘了关闭结果集,这个居然出bug了
    // issue #228 (close resultsets)
    closeResultSet(rsw.getResultSet());
  }
}
 
Example #12
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 #13
Source File: ExecutorTestHelper.java    From mybaties with 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 #14
Source File: Configuration.java    From Shop-for-JavaWeb with MIT License 6 votes vote down vote up
protected void checkLocallyForDiscriminatedNestedResultMaps(ResultMap rm) {
	if (!rm.hasNestedResultMaps() && rm.getDiscriminator() != null) {
		for (Map.Entry<String, String> entry : rm.getDiscriminator()
				.getDiscriminatorMap().entrySet()) {
			String discriminatedResultMapName = entry.getValue();
			if (hasResultMap(discriminatedResultMapName)) {
				ResultMap discriminatedResultMap = resultMaps
						.get(discriminatedResultMapName);
				if (discriminatedResultMap.hasNestedResultMaps()) {
					rm.forceNestedResultMaps();
					break;
				}
			}
		}
	}
}
 
Example #15
Source File: ExecutorTestHelper.java    From mybaties with 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 #16
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 #17
Source File: DefaultResultSetHandler.java    From mybaties with Apache License 2.0 6 votes vote down vote up
private void createRowKeyForUnmappedProperties(ResultMap resultMap, ResultSetWrapper rsw, CacheKey cacheKey, String columnPrefix) throws SQLException {
  final MetaClass metaType = MetaClass.forClass(resultMap.getType());
  List<String> unmappedColumnNames = rsw.getUnmappedColumnNames(resultMap, columnPrefix);
  for (String column : unmappedColumnNames) {
    String property = column;
    if (columnPrefix != null && !columnPrefix.isEmpty()) {
      // When columnPrefix is specified, ignore columns without the prefix.
      if (column.toUpperCase(Locale.ENGLISH).startsWith(columnPrefix)) {
        property = column.substring(columnPrefix.length());
      } else {
        continue;
      }
    }
    if (metaType.findProperty(property, configuration.isMapUnderscoreToCamelCase()) != null) {
      String value = rsw.getResultSet().getString(column);
      if (value != null) {
        cacheKey.update(column);
        cacheKey.update(value);
      }
    }
  }
}
 
Example #18
Source File: DefaultResultSetHandler.java    From mybatis with Apache License 2.0 6 votes vote down vote up
private Object createResultObject(ResultSetWrapper rsw, ResultMap resultMap, List<Class<?>> constructorArgTypes, List<Object> constructorArgs, String columnPrefix)
     throws SQLException {
//得到result type
   final Class<?> resultType = resultMap.getType();
   final MetaClass metaType = MetaClass.forClass(resultType);
   final List<ResultMapping> constructorMappings = resultMap.getConstructorResultMappings();
   if (typeHandlerRegistry.hasTypeHandler(resultType)) {
     //基本型
     return createPrimitiveResultObject(rsw, resultMap, columnPrefix);
   } else if (!constructorMappings.isEmpty()) {
     //有参数的构造函数
     return createParameterizedResultObject(rsw, resultType, constructorMappings, constructorArgTypes, constructorArgs, columnPrefix);
   } else if (resultType.isInterface() || metaType.hasDefaultConstructor()) {
     //普通bean类型
     return objectFactory.create(resultType);
   } else if (shouldApplyAutomaticMappings(resultMap, false)) {
     //自动映射
     return createByConstructorSignature(rsw, resultType, constructorArgTypes, constructorArgs, columnPrefix);
   }
   throw new ExecutorException("Do not know how to create an instance of " + resultType);
 }
 
Example #19
Source File: DefaultResultSetHandler.java    From mybatis with Apache License 2.0 6 votes vote down vote up
private void handleRowValuesForNestedResultMap(ResultSetWrapper rsw, ResultMap resultMap, ResultHandler resultHandler, RowBounds rowBounds, ResultMapping parentMapping) throws SQLException {
  final DefaultResultContext resultContext = new DefaultResultContext();
  skipRows(rsw.getResultSet(), rowBounds);
  Object rowValue = null;
  while (shouldProcessMoreRows(resultContext, rowBounds) && rsw.getResultSet().next()) {
    final ResultMap discriminatedResultMap = resolveDiscriminatedResultMap(rsw.getResultSet(), resultMap, null);
    final CacheKey rowKey = createRowKey(discriminatedResultMap, rsw, null);
    Object partialObject = nestedResultObjects.get(rowKey);
    // issue #577 && #542
    if (mappedStatement.isResultOrdered()) {
      if (partialObject == null && rowValue != null) {
        nestedResultObjects.clear();
        storeObject(resultHandler, resultContext, rowValue, parentMapping, rsw.getResultSet());
      }
      rowValue = getRowValue(rsw, discriminatedResultMap, rowKey, rowKey, null, partialObject);
    } else {
      rowValue = getRowValue(rsw, discriminatedResultMap, rowKey, rowKey, null, partialObject);
      if (partialObject == null) {
        storeObject(resultHandler, resultContext, rowValue, parentMapping, rsw.getResultSet());
      }
    }
  }
  if (rowValue != null && mappedStatement.isResultOrdered() && shouldProcessMoreRows(resultContext, rowBounds)) {
    storeObject(resultHandler, resultContext, rowValue, parentMapping, rsw.getResultSet());
  }
}
 
Example #20
Source File: MapperEnhancer.java    From tsharding with MIT License 6 votes vote down vote up
protected MappedStatement copyFromMappedStatement(MappedStatement ms,
                                                  SqlSource newSqlSource, String newMsId) {
    MappedStatement.Builder builder = new MappedStatement.Builder(ms.getConfiguration(), newMsId, newSqlSource, ms.getSqlCommandType());
    builder.resource(ms.getResource());
    builder.fetchSize(ms.getFetchSize());
    builder.statementType(ms.getStatementType());
    builder.keyGenerator(ms.getKeyGenerator());
    // setStatementTimeout()
    builder.timeout(ms.getTimeout());
    // setParameterMap()
    builder.parameterMap(ms.getParameterMap());
    // setStatementResultMap()
    List<ResultMap> resultMaps = ms.getResultMaps();
    builder.resultMaps(resultMaps);
    builder.resultSetType(ms.getResultSetType());
    // setStatementCache()
    builder.cache(ms.getCache());
    builder.flushCacheRequired(ms.isFlushCacheRequired());
    builder.useCache(ms.isUseCache());
    return builder.build();
}
 
Example #21
Source File: DefaultResultSetHandler.java    From mybatis with Apache License 2.0 6 votes vote down vote up
public ResultMap resolveDiscriminatedResultMap(ResultSet rs, ResultMap resultMap, String columnPrefix) throws SQLException {
  Set<String> pastDiscriminators = new HashSet<String>();
  Discriminator discriminator = resultMap.getDiscriminator();
  while (discriminator != null) {
    final Object value = getDiscriminatorValue(rs, discriminator, columnPrefix);
    final String discriminatedMapId = discriminator.getMapIdFor(String.valueOf(value));
    if (configuration.hasResultMap(discriminatedMapId)) {
      resultMap = configuration.getResultMap(discriminatedMapId);
      Discriminator lastDiscriminator = discriminator;
      discriminator = resultMap.getDiscriminator();
      if (discriminator == lastDiscriminator || !pastDiscriminators.add(discriminatedMapId)) {
        break;
      }
    } else {
      break;
    }
  }
  return resultMap;
}
 
Example #22
Source File: DefaultResultSetHandler.java    From mybaties with Apache License 2.0 5 votes vote down vote up
private boolean shouldApplyAutomaticMappings(ResultMap resultMap, boolean isNested) {
  if (resultMap.getAutoMapping() != null) {
    return resultMap.getAutoMapping();
  } else {
    if (isNested) {
      return AutoMappingBehavior.FULL == configuration.getAutoMappingBehavior();
    } else {
      return AutoMappingBehavior.NONE != configuration.getAutoMappingBehavior();
    }
  }
}
 
Example #23
Source File: DefaultResultSetHandler.java    From mybaties with Apache License 2.0 5 votes vote down vote up
private List<ResultMapping> getResultMappingsForRowKey(ResultMap resultMap) {
  List<ResultMapping> resultMappings = resultMap.getIdResultMappings();
  if (resultMappings.size() == 0) {
    resultMappings = resultMap.getPropertyResultMappings();
  }
  return resultMappings;
}
 
Example #24
Source File: DefaultResultSetHandler.java    From mybaties with Apache License 2.0 5 votes vote down vote up
private void handleRefCursorOutputParameter(ResultSet rs, ParameterMapping parameterMapping, MetaObject metaParam) throws SQLException {
  try {
    final String resultMapId = parameterMapping.getResultMapId();
    final ResultMap resultMap = configuration.getResultMap(resultMapId);
    final DefaultResultHandler resultHandler = new DefaultResultHandler(objectFactory);
    final ResultSetWrapper rsw = new ResultSetWrapper(rs, configuration);
    //里面就和一般ResultSet处理没两样了
    handleRowValues(rsw, resultMap, resultHandler, new RowBounds(), null);
    metaParam.setValue(parameterMapping.getProperty(), resultHandler.getResultList());
  } finally {
    // issue #228 (close resultsets)
    closeResultSet(rs);
  }
}
 
Example #25
Source File: MapperBuilderAssistant.java    From mybaties with Apache License 2.0 5 votes vote down vote up
private void setStatementResultMap(
    String resultMap,
    Class<?> resultType,
    ResultSetType resultSetType,
    MappedStatement.Builder statementBuilder) {
  resultMap = applyCurrentNamespace(resultMap, true);

  List<ResultMap> resultMaps = new ArrayList<ResultMap>();
  if (resultMap != null) {
    //2.1 resultMap是高级功能
    String[] resultMapNames = resultMap.split(",");
    for (String resultMapName : resultMapNames) {
      try {
        resultMaps.add(configuration.getResultMap(resultMapName.trim()));
      } catch (IllegalArgumentException e) {
        throw new IncompleteElementException("Could not find result map " + resultMapName, e);
      }
    }
  } else if (resultType != null) {
    //2.2 resultType,一般用这个足矣了
    //<select id="selectUsers" resultType="User">
    //这种情况下,MyBatis 会在幕后自动创建一个 ResultMap,基于属性名来映射列到 JavaBean 的属性上。
    //如果列名没有精确匹配,你可以在列名上使用 select 字句的别名来匹配标签。
    //创建一个inline result map, 把resultType设上就OK了,
    //然后后面被DefaultResultSetHandler.createResultObject()使用
    //DefaultResultSetHandler.getRowValue()使用
    ResultMap.Builder inlineResultMapBuilder = new ResultMap.Builder(
        configuration,
        statementBuilder.id() + "-Inline",
        resultType,
        new ArrayList<ResultMapping>(),
        null);
    resultMaps.add(inlineResultMapBuilder.build());
  }
  statementBuilder.resultMaps(resultMaps);

  statementBuilder.resultSetType(resultSetType);
}
 
Example #26
Source File: NameStyleTest.java    From Mapper with MIT License 5 votes vote down vote up
@Test
public void testLowercase(){
    EntityHelper.initEntityNameMap(UserLowercase.class, config);
    EntityTable entityTable = EntityHelper.getEntityTable(UserLowercase.class);
    Assert.assertNotNull(entityTable);
    Assert.assertEquals("userlowercase", entityTable.getName());

    Set<EntityColumn> columns = entityTable.getEntityClassColumns();
    Assert.assertEquals(1, columns.size());

    for (EntityColumn column : columns) {
        Assert.assertEquals("username", column.getColumn());
        Assert.assertEquals("userName", column.getProperty());

        Assert.assertEquals("username = #{userName}", column.getColumnEqualsHolder());
        Assert.assertEquals("username = #{record.userName}", column.getColumnEqualsHolder("record"));
        Assert.assertEquals("#{userName}", column.getColumnHolder());
        Assert.assertEquals("#{record.userName}", column.getColumnHolder("record"));
        Assert.assertEquals("#{record.userName}", column.getColumnHolder("record", "suffix"));
        Assert.assertEquals("#{record.userNamesuffix},", column.getColumnHolder("record", "suffix", ","));
        Assert.assertNull(column.getTypeHandler());
    }

    ResultMap resultMap = entityTable.getResultMap(configuration);
    Assert.assertEquals("[USERNAME]", resultMap.getMappedColumns().toString());

    Assert.assertEquals(1, resultMap.getResultMappings().size());

    ResultMapping resultMapping = resultMap.getResultMappings().get(0);
    Assert.assertEquals("username", resultMapping.getColumn());
    Assert.assertEquals("userName", resultMapping.getProperty());
    Assert.assertNull(resultMapping.getJdbcType());
    Assert.assertEquals(StringTypeHandler.class, resultMapping.getTypeHandler().getClass());
}
 
Example #27
Source File: Configuration.java    From mybaties with Apache License 2.0 5 votes vote down vote up
protected void checkLocallyForDiscriminatedNestedResultMaps(ResultMap rm) {
  if (!rm.hasNestedResultMaps() && rm.getDiscriminator() != null) {
    for (Map.Entry<String, String> entry : rm.getDiscriminator().getDiscriminatorMap().entrySet()) {
      String discriminatedResultMapName = entry.getValue();
      if (hasResultMap(discriminatedResultMapName)) {
        ResultMap discriminatedResultMap = resultMaps.get(discriminatedResultMapName);
        if (discriminatedResultMap.hasNestedResultMaps()) {
          rm.forceNestedResultMaps();
          break;
        }
      }
    }
  }
}
 
Example #28
Source File: ExecutorTestHelper.java    From mybatis with 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 #29
Source File: DefaultResultSetHandler.java    From mybatis with Apache License 2.0 5 votes vote down vote up
private CacheKey createRowKey(ResultMap resultMap, ResultSetWrapper rsw, String columnPrefix) throws SQLException {
  final CacheKey cacheKey = new CacheKey();
  cacheKey.update(resultMap.getId());
  List<ResultMapping> resultMappings = getResultMappingsForRowKey(resultMap);
  if (resultMappings.size() == 0) {
    if (Map.class.isAssignableFrom(resultMap.getType())) {
      createRowKeyForMap(rsw, cacheKey);
    } else {
      createRowKeyForUnmappedProperties(resultMap, rsw, cacheKey, columnPrefix);
    }
  } else {
    createRowKeyForMappedProperties(resultMap, rsw, cacheKey, resultMappings, columnPrefix);
  }
  return cacheKey;
}
 
Example #30
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;
}