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

The following examples show how to use org.apache.ibatis.mapping.ResultMap. 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: mybaties   Source File: XMLMapperBuilder.java    License: 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 Project: mybatis   Source File: DefaultResultSetHandler.java    License: 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 3
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 4
Source Project: mybatis   Source File: DefaultResultSetHandler.java    License: 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 Project: mybatis   Source File: XMLMapperBuilder.java    License: 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 6
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 7
Source Project: Shop-for-JavaWeb   Source File: Configuration.java    License: 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 8
Source Project: tsharding   Source File: MapperEnhancer.java    License: 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 9
Source Project: mybatis   Source File: DefaultResultSetHandler.java    License: 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 10
Source Project: mybaties   Source File: DefaultResultSetHandler.java    License: 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 11
Source Project: mybatis   Source File: DefaultResultSetHandler.java    License: 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 12
Source Project: mybaties   Source File: DefaultResultSetHandler.java    License: 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 13
Source Project: mybaties   Source File: DefaultResultSetHandler.java    License: 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 14
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 15
Source Project: mybaties   Source File: DefaultResultSetHandler.java    License: 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 16
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 17
Source Project: mybaties   Source File: DefaultResultSetHandler.java    License: 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 Project: mybatis   Source File: DefaultResultSetHandler.java    License: 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 Project: mybatis   Source File: DefaultResultSetHandler.java    License: 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 20
Source Project: mybaties   Source File: ExecutorTestHelper.java    License: Apache License 2.0 6 votes vote down vote up
public static MappedStatement prepareSelectAuthorViaOutParams(final Configuration config) {
  final TypeHandlerRegistry registry = config.getTypeHandlerRegistry();
  MappedStatement ms = new MappedStatement.Builder(config, "selectAuthorViaOutParams", new StaticSqlSource(config, "{call selectAuthorViaOutParams(?,?,?,?,?)}"), SqlCommandType.SELECT)
      .statementType(StatementType.CALLABLE)
      .parameterMap(new ParameterMap.Builder(config, "defaultParameterMap", Author.class,
          new ArrayList<ParameterMapping>() {
            {
              add(new ParameterMapping.Builder(config, "id", registry.getTypeHandler(int.class)).build());
              add(new ParameterMapping.Builder(config, "username", registry.getTypeHandler(String.class)).jdbcType(JdbcType.VARCHAR).mode(ParameterMode.OUT).build());
              add(new ParameterMapping.Builder(config, "password", registry.getTypeHandler(String.class)).jdbcType(JdbcType.VARCHAR).mode(ParameterMode.OUT).build());
              add(new ParameterMapping.Builder(config, "email", registry.getTypeHandler(String.class)).jdbcType(JdbcType.VARCHAR).mode(ParameterMode.OUT).build());
              add(new ParameterMapping.Builder(config, "bio", registry.getTypeHandler(String.class)).jdbcType(JdbcType.VARCHAR).mode(ParameterMode.OUT).build());
            }
          }).build())
      .resultMaps(new ArrayList<ResultMap>())
      .cache(authorCache).build();
  return ms;
}
 
Example 21
Source Project: mybaties   Source File: ExecutorTestHelper.java    License: Apache License 2.0 6 votes vote down vote up
public static MappedStatement createSelectAuthorWithIDof99MappedStatement(final Configuration config) {
  final TypeHandlerRegistry registry = config.getTypeHandlerRegistry();
  MappedStatement ms = new MappedStatement.Builder(config, "selectAuthor", new StaticSqlSource(config,"SELECT * FROM author WHERE id = 99"), SqlCommandType.SELECT)
      .statementType(StatementType.STATEMENT)
      .parameterMap(new ParameterMap.Builder(config, "defaultParameterMap", Author.class, new ArrayList<ParameterMapping>()).build())
      .resultMaps(new ArrayList<ResultMap>() {
        {
          add(new ResultMap.Builder(config, "defaultResultMap", Author.class, new ArrayList<ResultMapping>() {
            {
              add(new ResultMapping.Builder(config, "id", "id", registry.getTypeHandler(int.class)).build());
              add(new ResultMapping.Builder(config, "username", "username", registry.getTypeHandler(String.class)).build());
              add(new ResultMapping.Builder(config, "password", "password", registry.getTypeHandler(String.class)).build());
              add(new ResultMapping.Builder(config, "email", "email", registry.getTypeHandler(String.class)).build());
              add(new ResultMapping.Builder(config, "bio", "bio", registry.getTypeHandler(String.class)).build());
            }
          }).build());
        }
      }).build();
  return ms;
}
 
Example 22
Source Project: Mapper   Source File: NameStyleTest.java    License: MIT License 5 votes vote down vote up
@Test
public void testCamelhump(){
    EntityHelper.initEntityNameMap(UserCamelhump.class, config);
    EntityTable entityTable = EntityHelper.getEntityTable(UserCamelhump.class);
    Assert.assertNotNull(entityTable);
    Assert.assertEquals("user_camelhump", entityTable.getName());

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

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

        Assert.assertEquals("user_name = #{userName}", column.getColumnEqualsHolder());
        Assert.assertEquals("user_name = #{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("[USER_NAME]", resultMap.getMappedColumns().toString());

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

    ResultMapping resultMapping = resultMap.getResultMappings().get(0);
    Assert.assertEquals("user_name", resultMapping.getColumn());
    Assert.assertEquals("userName", resultMapping.getProperty());
    Assert.assertNull(resultMapping.getJdbcType());
    Assert.assertEquals(StringTypeHandler.class, resultMapping.getTypeHandler().getClass());
}
 
Example 23
Source Project: mybatis   Source File: ExecutorTestHelper.java    License: Apache License 2.0 5 votes vote down vote up
public static MappedStatement prepareSelectBlogByIdAndAuthor(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 = ? and a.id = ?");
  final ParameterMap parameterMap = new ParameterMap.Builder(config, "defaultParameterMap", Map.class,
      new ArrayList<ParameterMapping>() {
        {
          add(new ParameterMapping.Builder(config, "blogId", registry.getTypeHandler(int.class)).build());
          add(new ParameterMapping.Builder(config, "authorId", 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, "selectBlogByIdAndAuthor", sqlSource, SqlCommandType.SELECT)
      .parameterMap(parameterMap)
      .resultMaps(new ArrayList<ResultMap>() {
        {
          add(resultMap);
        }
      }).build();

}
 
Example 24
Source Project: mybatis   Source File: DefaultResultSetHandler.java    License: Apache License 2.0 5 votes vote down vote up
private void handleRowValues(ResultSetWrapper rsw, ResultMap resultMap, ResultHandler resultHandler, RowBounds rowBounds, ResultMapping parentMapping) throws SQLException {
  if (resultMap.hasNestedResultMaps()) {
    ensureNoRowBounds();
    checkResultHandler();
    handleRowValuesForNestedResultMap(rsw, resultMap, resultHandler, rowBounds, parentMapping);
  } else {
    handleRowValuesForSimpleResultMap(rsw, resultMap, resultHandler, rowBounds, parentMapping);
  }
}
 
Example 25
Source Project: mybatis   Source File: DefaultResultSetHandler.java    License: 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 26
Source Project: Mapper   Source File: ColumnTypeTest.java    License: MIT License 5 votes vote down vote up
@Test
public void testJdbcTypeBlob(){
    EntityHelper.initEntityNameMap(UserJdbcTypeBlob.class, config);
    EntityTable entityTable = EntityHelper.getEntityTable(UserJdbcTypeBlob.class);
    Assert.assertNotNull(entityTable);

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

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

        Assert.assertEquals("name = #{name, jdbcType=BLOB}", column.getColumnEqualsHolder());
        Assert.assertEquals("name = #{record.name, jdbcType=BLOB}", column.getColumnEqualsHolder("record"));
        Assert.assertEquals("#{name, jdbcType=BLOB}", column.getColumnHolder());
        Assert.assertEquals("#{record.name, jdbcType=BLOB}", column.getColumnHolder("record"));
        Assert.assertEquals("#{record.name, jdbcType=BLOB}", column.getColumnHolder("record", "suffix"));
        Assert.assertEquals("#{record.namesuffix, jdbcType=BLOB},", column.getColumnHolder("record", "suffix", ","));
        Assert.assertNull(column.getTypeHandler());
    }

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

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

    ResultMapping resultMapping = resultMap.getResultMappings().get(0);
    Assert.assertEquals("name", resultMapping.getColumn());
    Assert.assertEquals("name", resultMapping.getProperty());
    Assert.assertNotNull(resultMapping.getJdbcType());
    Assert.assertEquals(JdbcType.BLOB, resultMapping.getJdbcType());
    Assert.assertEquals(StringTypeHandler.class, resultMapping.getTypeHandler().getClass());
}
 
Example 27
Source Project: Mapper   Source File: NameStyleTest.java    License: MIT License 5 votes vote down vote up
@Test
public void testCamelhumpAndLowercase(){
    EntityHelper.initEntityNameMap(UserCamelhumpAndLowercase.class, config);
    EntityTable entityTable = EntityHelper.getEntityTable(UserCamelhumpAndLowercase.class);
    Assert.assertNotNull(entityTable);
    Assert.assertEquals("user_camelhump_and_lowercase", entityTable.getName());

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

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

        Assert.assertEquals("user_name = #{userName}", column.getColumnEqualsHolder());
        Assert.assertEquals("user_name = #{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("[USER_NAME]", resultMap.getMappedColumns().toString());

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

    ResultMapping resultMapping = resultMap.getResultMappings().get(0);
    Assert.assertEquals("user_name", resultMapping.getColumn());
    Assert.assertEquals("userName", resultMapping.getProperty());
    Assert.assertNull(resultMapping.getJdbcType());
    Assert.assertEquals(StringTypeHandler.class, resultMapping.getTypeHandler().getClass());
}
 
Example 28
@Override
protected void setResultType(MappedStatement ms, Class<?> entityClass) {
    List<ResultMap> resultMaps = new ArrayList<>();
    resultMaps.add(getResultMap(entityClass, ms.getConfiguration()));
    MetaObject metaObject = SystemMetaObject.forObject(ms);
    metaObject.setValue("resultMaps", Collections.unmodifiableList(resultMaps));
}
 
Example 29
private ResultMap getResultMap(final Class<?> entityClass, final Configuration configuration) {
    ResultMap result = resultMapCache.getOrDefault(entityClass, null);
    if (result != null) {
        return result;
    } else {
        result = getResultMapInternal(entityClass, configuration);
        resultMapCache.put(entityClass, result);
        return result;
    }
}
 
Example 30
Source Project: Mapper   Source File: ColumnTypeTest.java    License: MIT License 5 votes vote down vote up
@Test
public void testColumn(){
    EntityHelper.initEntityNameMap(UserColumn.class, config);
    EntityTable entityTable = EntityHelper.getEntityTable(UserColumn.class);
    Assert.assertNotNull(entityTable);

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

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

        Assert.assertEquals("user_name = #{name}", column.getColumnEqualsHolder());
        Assert.assertEquals("user_name = #{record.name}", column.getColumnEqualsHolder("record"));
        Assert.assertEquals("#{name}", column.getColumnHolder());
        Assert.assertEquals("#{record.name}", column.getColumnHolder("record"));
        Assert.assertEquals("#{record.name}", column.getColumnHolder("record", "suffix"));
        Assert.assertEquals("#{record.namesuffix},", column.getColumnHolder("record", "suffix", ","));
        Assert.assertNull(column.getTypeHandler());
    }

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

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

    ResultMapping resultMapping = resultMap.getResultMappings().get(0);
    Assert.assertEquals("user_name", resultMapping.getColumn());
    Assert.assertEquals("name", resultMapping.getProperty());
    Assert.assertNull(resultMapping.getJdbcType());
    Assert.assertEquals(StringTypeHandler.class, resultMapping.getTypeHandler().getClass());
}