Java Code Examples for org.apache.ibatis.executor.ExecutorException

The following examples show how to use org.apache.ibatis.executor.ExecutorException. 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: tk-mybatis   Source File: SelectKeyGenerator.java    License: MIT License 6 votes vote down vote up
private void handleMultipleProperties(String[] keyProperties,
                                      MetaObject metaParam, MetaObject metaResult) {
    String[] keyColumns = keyStatement.getKeyColumns();

    if (keyColumns == null || keyColumns.length == 0) {
        // no key columns specified, just use the property names
        for (String keyProperty : keyProperties) {
            setValue(metaParam, keyProperty, metaResult.getValue(keyProperty));
        }
    } else {
        if (keyColumns.length != keyProperties.length) {
            throw new ExecutorException("If SelectKey has key columns, the number must match the number of key properties.");
        }
        for (int i = 0; i < keyProperties.length; i++) {
            setValue(metaParam, keyProperties[i], metaResult.getValue(keyColumns[i]));
        }
    }
}
 
Example 2
Source Project: mybaties   Source File: DefaultResultSetHandler.java    License: Apache License 2.0 6 votes vote down vote up
private Object instantiateCollectionPropertyIfAppropriate(ResultMapping resultMapping, MetaObject metaObject) {
  final String propertyName = resultMapping.getProperty();
  Object propertyValue = metaObject.getValue(propertyName);
  if (propertyValue == null) {
    Class<?> type = resultMapping.getJavaType();
    if (type == null) {
      type = metaObject.getSetterType(propertyName);
    }
    try {
      if (objectFactory.isCollection(type)) {
        propertyValue = objectFactory.create(type);
        metaObject.setValue(propertyName, propertyValue);
        return propertyValue;
      }
    } catch (Exception e) {
      throw new ExecutorException("Error instantiating collection property for result '" + resultMapping.getProperty() + "'.  Cause: " + e, e);
    }
  } else if (objectFactory.isCollection(propertyValue.getClass())) {
    return propertyValue;
  }
  return null;
}
 
Example 3
Source Project: mybaties   Source File: DefaultResultSetHandler.java    License: Apache License 2.0 6 votes vote down vote up
private void addPendingChildRelation(ResultSet rs, MetaObject metaResultObject, ResultMapping parentMapping) throws SQLException {
  CacheKey cacheKey = createKeyForMultipleResults(rs, parentMapping, parentMapping.getColumn(), parentMapping.getColumn());
  PendingRelation deferLoad = new PendingRelation();
  deferLoad.metaObject = metaResultObject;
  deferLoad.propertyMapping = parentMapping;
  List<PendingRelation> relations = pendingRelations.get(cacheKey);
  // issue #255
  if (relations == null) {
    relations = new ArrayList<DefaultResultSetHandler.PendingRelation>();
    pendingRelations.put(cacheKey, relations);
  }
  relations.add(deferLoad);
  ResultMapping previous = nextResultMaps.get(parentMapping.getResultSet());
  if (previous == null) {
    nextResultMaps.put(parentMapping.getResultSet(), parentMapping);
  } else {
    if (!previous.equals(parentMapping)) {
      throw new ExecutorException("Two different properties are mapped to the same resultSet");
    }
  }
}
 
Example 4
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 5
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 6
Source Project: mybaties   Source File: SelectKeyGenerator.java    License: Apache License 2.0 6 votes vote down vote up
private void handleMultipleProperties(String[] keyProperties,
    MetaObject metaParam, MetaObject metaResult) {
  String[] keyColumns = keyStatement.getKeyColumns();
    
  if (keyColumns == null || keyColumns.length == 0) {
    // no key columns specified, just use the property names
    for (int i = 0; i < keyProperties.length; i++) {
      setValue(metaParam, keyProperties[i], metaResult.getValue(keyProperties[i]));
    }
  } else {
    if (keyColumns.length != keyProperties.length) {
      throw new ExecutorException("If SelectKey has key columns, the number must match the number of key properties.");
    }
    for (int i = 0; i < keyProperties.length; i++) {
      setValue(metaParam, keyProperties[i], metaResult.getValue(keyColumns[i]));
    }
  }
}
 
Example 7
Source Project: mybaties   Source File: CallableStatementHandler.java    License: Apache License 2.0 6 votes vote down vote up
private void registerOutputParameters(CallableStatement cs) throws SQLException {
  List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
  for (int i = 0, n = parameterMappings.size(); i < n; i++) {
    ParameterMapping parameterMapping = parameterMappings.get(i);
    //只处理OUT|INOUT
    if (parameterMapping.getMode() == ParameterMode.OUT || parameterMapping.getMode() == ParameterMode.INOUT) {
      if (null == parameterMapping.getJdbcType()) {
        throw new ExecutorException("The JDBC Type must be specified for output parameter.  Parameter: " + parameterMapping.getProperty());
      } else {
        if (parameterMapping.getNumericScale() != null && (parameterMapping.getJdbcType() == JdbcType.NUMERIC || parameterMapping.getJdbcType() == JdbcType.DECIMAL)) {
          cs.registerOutParameter(i + 1, parameterMapping.getJdbcType().TYPE_CODE, parameterMapping.getNumericScale());
        } else {
          //核心是调用CallableStatement.registerOutParameter
          if (parameterMapping.getJdbcTypeName() == null) {
            cs.registerOutParameter(i + 1, parameterMapping.getJdbcType().TYPE_CODE);
          } else {
            cs.registerOutParameter(i + 1, parameterMapping.getJdbcType().TYPE_CODE, parameterMapping.getJdbcTypeName());
          }
        }
      }
    }
  }
}
 
Example 8
Source Project: mybaties   Source File: RoutingStatementHandler.java    License: Apache License 2.0 6 votes vote down vote up
public RoutingStatementHandler(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {

    //根据语句类型,委派到不同的语句处理器(STATEMENT|PREPARED|CALLABLE)
    switch (ms.getStatementType()) {
      case STATEMENT:
        delegate = new SimpleStatementHandler(executor, ms, parameter, rowBounds, resultHandler, boundSql);
        break;
      case PREPARED:
        delegate = new PreparedStatementHandler(executor, ms, parameter, rowBounds, resultHandler, boundSql);
        break;
      case CALLABLE:
        delegate = new CallableStatementHandler(executor, ms, parameter, rowBounds, resultHandler, boundSql);
        break;
      default:
        throw new ExecutorException("Unknown statement type: " + ms.getStatementType());
    }

  }
 
Example 9
Source Project: mybaties   Source File: GeneralExceptionsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldInstantiateAndThrowAllCustomExceptions() throws Exception {
  Class<?>[] exceptionTypes = {
      BindingException.class,
      CacheException.class,
      DataSourceException.class,
      ExecutorException.class,
      LogException.class,
      ParsingException.class,
      BuilderException.class,
      PluginException.class,
      ReflectionException.class,
      PersistenceException.class,
      SqlSessionException.class,
      TransactionException.class,
      TypeException.class, 
      ScriptingException.class
  };
  for (Class<?> exceptionType : exceptionTypes) {
    testExceptionConstructors(exceptionType);
  }

}
 
Example 10
Source Project: Mapper   Source File: SelectKeyGenerator.java    License: MIT License 6 votes vote down vote up
private void handleMultipleProperties(String[] keyProperties,
                                      MetaObject metaParam, MetaObject metaResult) {
    String[] keyColumns = keyStatement.getKeyColumns();

    if (keyColumns == null || keyColumns.length == 0) {
        // no key columns specified, just use the property names
        for (String keyProperty : keyProperties) {
            setValue(metaParam, keyProperty, metaResult.getValue(keyProperty));
        }
    } else {
        if (keyColumns.length != keyProperties.length) {
            throw new ExecutorException("If SelectKey has key columns, the number must match the number of key properties.");
        }
        for (int i = 0; i < keyProperties.length; i++) {
            setValue(metaParam, keyProperties[i], metaResult.getValue(keyColumns[i]));
        }
    }
}
 
Example 11
Source Project: mybatis   Source File: DefaultResultSetHandler.java    License: Apache License 2.0 6 votes vote down vote up
private Object instantiateCollectionPropertyIfAppropriate(ResultMapping resultMapping, MetaObject metaObject) {
  final String propertyName = resultMapping.getProperty();
  Object propertyValue = metaObject.getValue(propertyName);
  if (propertyValue == null) {
    Class<?> type = resultMapping.getJavaType();
    if (type == null) {
      type = metaObject.getSetterType(propertyName);
    }
    try {
      if (objectFactory.isCollection(type)) {
        propertyValue = objectFactory.create(type);
        metaObject.setValue(propertyName, propertyValue);
        return propertyValue;
      }
    } catch (Exception e) {
      throw new ExecutorException("Error instantiating collection property for result '" + resultMapping.getProperty() + "'.  Cause: " + e, e);
    }
  } else if (objectFactory.isCollection(propertyValue.getClass())) {
    return propertyValue;
  }
  return null;
}
 
Example 12
Source Project: mybatis   Source File: DefaultResultSetHandler.java    License: Apache License 2.0 6 votes vote down vote up
private void addPendingChildRelation(ResultSet rs, MetaObject metaResultObject, ResultMapping parentMapping) throws SQLException {
  CacheKey cacheKey = createKeyForMultipleResults(rs, parentMapping, parentMapping.getColumn(), parentMapping.getColumn());
  PendingRelation deferLoad = new PendingRelation();
  deferLoad.metaObject = metaResultObject;
  deferLoad.propertyMapping = parentMapping;
  List<PendingRelation> relations = pendingRelations.get(cacheKey);
  // issue #255
  if (relations == null) {
    relations = new ArrayList<DefaultResultSetHandler.PendingRelation>();
    pendingRelations.put(cacheKey, relations);
  }
  relations.add(deferLoad);
  ResultMapping previous = nextResultMaps.get(parentMapping.getResultSet());
  if (previous == null) {
    nextResultMaps.put(parentMapping.getResultSet(), parentMapping);
  } else {
    if (!previous.equals(parentMapping)) {
      throw new ExecutorException("Two different properties are mapped to the same resultSet");
    }
  }
}
 
Example 13
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 14
Source Project: mybatis   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 15
Source Project: mybatis   Source File: SelectKeyGenerator.java    License: Apache License 2.0 6 votes vote down vote up
private void handleMultipleProperties(String[] keyProperties,
    MetaObject metaParam, MetaObject metaResult) {
  String[] keyColumns = keyStatement.getKeyColumns();
    
  if (keyColumns == null || keyColumns.length == 0) {
    // no key columns specified, just use the property names
    for (int i = 0; i < keyProperties.length; i++) {
      setValue(metaParam, keyProperties[i], metaResult.getValue(keyProperties[i]));
    }
  } else {
    if (keyColumns.length != keyProperties.length) {
      throw new ExecutorException("If SelectKey has key columns, the number must match the number of key properties.");
    }
    for (int i = 0; i < keyProperties.length; i++) {
      setValue(metaParam, keyProperties[i], metaResult.getValue(keyColumns[i]));
    }
  }
}
 
Example 16
Source Project: mybatis   Source File: CallableStatementHandler.java    License: Apache License 2.0 6 votes vote down vote up
private void registerOutputParameters(CallableStatement cs) throws SQLException {
  List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
  for (int i = 0, n = parameterMappings.size(); i < n; i++) {
    ParameterMapping parameterMapping = parameterMappings.get(i);
    //只处理OUT|INOUT
    if (parameterMapping.getMode() == ParameterMode.OUT || parameterMapping.getMode() == ParameterMode.INOUT) {
      if (null == parameterMapping.getJdbcType()) {
        throw new ExecutorException("The JDBC Type must be specified for output parameter.  Parameter: " + parameterMapping.getProperty());
      } else {
        if (parameterMapping.getNumericScale() != null && (parameterMapping.getJdbcType() == JdbcType.NUMERIC || parameterMapping.getJdbcType() == JdbcType.DECIMAL)) {
          cs.registerOutParameter(i + 1, parameterMapping.getJdbcType().TYPE_CODE, parameterMapping.getNumericScale());
        } else {
          //核心是调用CallableStatement.registerOutParameter
          if (parameterMapping.getJdbcTypeName() == null) {
            cs.registerOutParameter(i + 1, parameterMapping.getJdbcType().TYPE_CODE);
          } else {
            cs.registerOutParameter(i + 1, parameterMapping.getJdbcType().TYPE_CODE, parameterMapping.getJdbcTypeName());
          }
        }
      }
    }
  }
}
 
Example 17
Source Project: mybatis   Source File: RoutingStatementHandler.java    License: Apache License 2.0 6 votes vote down vote up
public RoutingStatementHandler(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {

    //根据语句类型,委派到不同的语句处理器(STATEMENT|PREPARED|CALLABLE)
    switch (ms.getStatementType()) {
      case STATEMENT:
        delegate = new SimpleStatementHandler(executor, ms, parameter, rowBounds, resultHandler, boundSql);
        break;
      case PREPARED:
        delegate = new PreparedStatementHandler(executor, ms, parameter, rowBounds, resultHandler, boundSql);
        break;
      case CALLABLE:
        delegate = new CallableStatementHandler(executor, ms, parameter, rowBounds, resultHandler, boundSql);
        break;
      default:
        throw new ExecutorException("Unknown statement type: " + ms.getStatementType());
    }

  }
 
Example 18
Source Project: mybatis   Source File: GeneralExceptionsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldInstantiateAndThrowAllCustomExceptions() throws Exception {
  Class<?>[] exceptionTypes = {
      BindingException.class,
      CacheException.class,
      DataSourceException.class,
      ExecutorException.class,
      LogException.class,
      ParsingException.class,
      BuilderException.class,
      PluginException.class,
      ReflectionException.class,
      PersistenceException.class,
      SqlSessionException.class,
      TransactionException.class,
      TypeException.class, 
      ScriptingException.class
  };
  for (Class<?> exceptionType : exceptionTypes) {
    testExceptionConstructors(exceptionType);
  }

}
 
Example 19
Source Project: tk-mybatis   Source File: SelectKeyGenerator.java    License: MIT License 5 votes vote down vote up
private void setValue(MetaObject metaParam, String property, Object value) {
    if (metaParam.hasSetter(property)) {
        if(metaParam.hasGetter(property)){
            Object defaultValue = metaParam.getValue(property);
            if(defaultValue != null){
                return;
            }
        }
        metaParam.setValue(property, value);
    } else {
        throw new ExecutorException("No setter found for the keyProperty '" + property + "' in " + metaParam.getOriginalObject().getClass().getName() + ".");
    }
}
 
Example 20
Source Project: mybatis-jpa   Source File: IdentityKeyGenerator.java    License: Apache License 2.0 5 votes vote down vote up
public void processGeneratedKeys(MappedStatement ms, Statement stmt, Object parameter) {
  final String[] keyProperties = ms.getKeyProperties();
  if (keyProperties == null || keyProperties.length == 0) {
    return;
  }
  if (keyProperties.length > 1) {
    throw new ExecutorException(
        "There are more than one keyProperty in MappedStatement : " + ms.getId() + ".");
  }

  if (parameter instanceof Collection) {
    handleCollection(ms, stmt, (Collection) parameter);
  } else if (parameter.getClass().isArray()) {
    handleCollection(ms, stmt, Arrays.asList(parameter));
  } else if (parameter instanceof Map) {
    Map parameterMap = (Map) parameter;
    if (parameterMap.containsKey("collection")) {
      handleCollection(ms, stmt, (Collection) parameterMap.get("collection"));
    } else if (parameterMap.containsKey("list")) {
      handleCollection(ms, stmt, (List) parameterMap.get("list"));
    } else if (parameterMap.containsKey("array")) {
      handleCollection(ms, stmt, Arrays.asList((Object[]) parameterMap.get("array")));
    }
  } else {
    handleObject(ms, stmt, parameter, idGenerator.nextId());
  }
}
 
Example 21
Source Project: mybatis-jpa   Source File: IdentityKeyGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private void setValue(MetaObject metaParam, String property, Object value) {
  if (metaParam.hasSetter(property)) {
    metaParam.setValue(property, value);
  } else {
    throw new ExecutorException(
        "No setter found for the keyProperty '" + property + "' in " + metaParam
            .getOriginalObject().getClass().getName() + ".");
  }
}
 
Example 22
Source Project: AsuraFramework   Source File: DefaultParameterHandler.java    License: Apache License 2.0 5 votes vote down vote up
public void setParameters(PreparedStatement ps) throws SQLException {
    ErrorContext.instance().activity("setting parameters").object(mappedStatement.getParameterMap().getId());
    List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
    if (parameterMappings != null) {
        MetaObject metaObject = parameterObject == null ? null : configuration.newMetaObject(parameterObject);
        for (int i = 0; i < parameterMappings.size(); i++) {
            ParameterMapping parameterMapping = parameterMappings.get(i);
            if (parameterMapping.getMode() != ParameterMode.OUT) {
                Object value;
                String propertyName = parameterMapping.getProperty();
                if (boundSql.hasAdditionalParameter(propertyName)) { // issue #448 ask first for additional params
                    value = boundSql.getAdditionalParameter(propertyName);
                } else if (parameterObject == null) {
                    value = null;
                } else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
                    value = parameterObject;
                } else {
                    value = metaObject == null ? null : metaObject.getValue(propertyName);
                }
                TypeHandler typeHandler = parameterMapping.getTypeHandler();
                if (typeHandler == null) {
                    throw new ExecutorException("There was no TypeHandler found for parameter " + propertyName + " of statement " + mappedStatement.getId());
                }
                JdbcType jdbcType = parameterMapping.getJdbcType();
                if (value == null && jdbcType == null) jdbcType = configuration.getJdbcTypeForNull();
                typeHandler.setParameter(ps, i + 1, value, jdbcType);
            }
        }
    }
}
 
Example 23
Source Project: Shop-for-JavaWeb   Source File: SQLHelper.java    License: MIT License 5 votes vote down vote up
/**
 * 对SQL参数(?)设值,参考org.apache.ibatis.executor.parameter.DefaultParameterHandler
 *
 * @param ps              表示预编译的 SQL 语句的对象。
 * @param mappedStatement MappedStatement
 * @param boundSql        SQL
 * @param parameterObject 参数对象
 * @throws java.sql.SQLException 数据库异常
 */
@SuppressWarnings("unchecked")
public static void setParameters(PreparedStatement ps, MappedStatement mappedStatement, BoundSql boundSql, Object parameterObject) throws SQLException {
    ErrorContext.instance().activity("setting parameters").object(mappedStatement.getParameterMap().getId());
    List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
    if (parameterMappings != null) {
        Configuration configuration = mappedStatement.getConfiguration();
        TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
        MetaObject metaObject = parameterObject == null ? null :
                configuration.newMetaObject(parameterObject);
        for (int i = 0; i < parameterMappings.size(); i++) {
            ParameterMapping parameterMapping = parameterMappings.get(i);
            if (parameterMapping.getMode() != ParameterMode.OUT) {
                Object value;
                String propertyName = parameterMapping.getProperty();
                PropertyTokenizer prop = new PropertyTokenizer(propertyName);
                if (parameterObject == null) {
                    value = null;
                } else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
                    value = parameterObject;
                } else if (boundSql.hasAdditionalParameter(propertyName)) {
                    value = boundSql.getAdditionalParameter(propertyName);
                } else if (propertyName.startsWith(ForEachSqlNode.ITEM_PREFIX) && boundSql.hasAdditionalParameter(prop.getName())) {
                    value = boundSql.getAdditionalParameter(prop.getName());
                    if (value != null) {
                        value = configuration.newMetaObject(value).getValue(propertyName.substring(prop.getName().length()));
                    }
                } else {
                    value = metaObject == null ? null : metaObject.getValue(propertyName);
                }
                @SuppressWarnings("rawtypes")
	TypeHandler typeHandler = parameterMapping.getTypeHandler();
                if (typeHandler == null) {
                    throw new ExecutorException("There was no TypeHandler found for parameter " + propertyName + " of statement " + mappedStatement.getId());
                }
                typeHandler.setParameter(ps, i + 1, value, parameterMapping.getJdbcType());
            }
        }
    }
}
 
Example 24
Source Project: spring-data-mybatis   Source File: SnowflakeKeyGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private void setValue(MetaObject metaParam, String property, Object value) {
	if (metaParam.hasSetter(property)) {
		metaParam.setValue(property, value);
	}
	else {
		throw new ExecutorException("No setter found for the keyProperty '" + property
				+ "' in " + metaParam.getOriginalObject().getClass().getName() + ".");
	}
}
 
Example 25
Source Project: mybaties   Source File: DefaultResultSetHandler.java    License: Apache License 2.0 5 votes vote down vote up
protected void checkResultHandler() {
  if (resultHandler != null && configuration.isSafeResultHandlerEnabled() && !mappedStatement.isResultOrdered()) {
    throw new ExecutorException("Mapped Statements with nested result mappings cannot be safely used with a custom ResultHandler. "
        + "Use safeResultHandlerEnabled=false setting to bypass this check " 
        + "or ensure your statement returns ordered data and set resultOrdered=true on it.");
  }
}
 
Example 26
Source Project: mybaties   Source File: DefaultResultSetHandler.java    License: Apache License 2.0 5 votes vote down vote up
private CacheKey combineKeys(CacheKey rowKey, CacheKey parentRowKey) {
  if (rowKey.getUpdateCount() > 1 && parentRowKey.getUpdateCount() > 1) {
    CacheKey combinedKey;
    try {
      combinedKey = rowKey.clone();
    } catch (CloneNotSupportedException e) {
      throw new ExecutorException("Error cloning cache key.  Cause: " + e, e);
    }
    combinedKey.update(parentRowKey);
    return combinedKey;
  }
  return CacheKey.NULL_CACHE_KEY;
}
 
Example 27
Source Project: mybaties   Source File: SelectKeyGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private void setValue(MetaObject metaParam, String property, Object value) {
  if (metaParam.hasSetter(property)) {
    metaParam.setValue(property, value);
  } else {
    throw new ExecutorException("No setter found for the keyProperty '" + property + "' in " + metaParam.getOriginalObject().getClass().getName() + ".");
  }
}
 
Example 28
Source Project: mybaties   Source File: ResultLoader.java    License: Apache License 2.0 5 votes vote down vote up
private Executor newExecutor() {
  final Environment environment = configuration.getEnvironment();
  if (environment == null) {
    throw new ExecutorException("ResultLoader could not load lazily.  Environment was not configured.");
  }
  final DataSource ds = environment.getDataSource();
  if (ds == null) {
    throw new ExecutorException("ResultLoader could not load lazily.  DataSource was not configured.");
  }
  final TransactionFactory transactionFactory = environment.getTransactionFactory();
  final Transaction tx = transactionFactory.newTransaction(ds, null, false);
  //如果executor已经被关闭了,则创建一个新的SimpleExecutor
  return configuration.newExecutor(tx, ExecutorType.SIMPLE);
}
 
Example 29
Source Project: mybaties   Source File: ResultLoaderMap.java    License: Apache License 2.0 5 votes vote down vote up
public void addLoader(String property, MetaObject metaResultObject, ResultLoader resultLoader) {
    String upperFirst = getUppercaseFirstProperty(property);
    if (!upperFirst.equalsIgnoreCase(property) && loaderMap.containsKey(upperFirst)) {
      throw new ExecutorException("Nested lazy loaded result property '" + property +
              "' for query id '" + resultLoader.mappedStatement.getId() +
              " already exists in the result map. The leftmost property of all lazy loaded properties must be unique within a result map.");
    }
    //key是property,这样当客户端调用getter来取真实值时,会判断这个属性是否是延迟加载属性,是才去加载
    //可参见CglibProxyFactory的代码
//    if (lazyLoader.hasLoader(property)) {
//        lazyLoader.load(property);
//    }
    loaderMap.put(upperFirst, new LoadPair(property, metaResultObject, resultLoader));
  }
 
Example 30
Source Project: mybaties   Source File: ResultLoaderMap.java    License: Apache License 2.0 5 votes vote down vote up
public void load(final Object userObject) throws SQLException {
  if (this.metaResultObject == null || this.resultLoader == null) {
    if (this.mappedParameter == null) {
      throw new ExecutorException("Property [" + this.property + "] cannot be loaded because "
              + "required parameter of mapped statement ["
              + this.mappedStatement + "] is not serializable.");
    }

    final Configuration config = this.getConfiguration();
    final MappedStatement ms = config.getMappedStatement(this.mappedStatement);
    if (ms == null) {
      throw new ExecutorException("Cannot lazy load property [" + this.property
              + "] of deserialized object [" + userObject.getClass()
              + "] because configuration does not contain statement ["
              + this.mappedStatement + "]");
    }

    this.metaResultObject = config.newMetaObject(userObject);
    this.resultLoader = new ResultLoader(config, new ClosedExecutor(), ms, this.mappedParameter,
            metaResultObject.getSetterType(this.property), null, null);
  }

  /* We are using a new executor because we may be (and likely are) on a new thread
   * and executors aren't thread safe. (Is this sufficient?)
   *
   * A better approach would be making executors thread safe. */
  if (this.serializationCheck == null) {
    final ResultLoader old = this.resultLoader;
    this.resultLoader = new ResultLoader(old.configuration, new ClosedExecutor(), old.mappedStatement,
            old.parameterObject, old.targetType, old.cacheKey, old.boundSql);
  }

  this.metaResultObject.setValue(property, this.resultLoader.loadResult());
}