Java Code Examples for org.apache.ibatis.session.Configuration#newMetaObject()

The following examples show how to use org.apache.ibatis.session.Configuration#newMetaObject() . 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: RollupResultHandler.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private static Object coalesceResults(Configuration configuration, List<Object> valueObjects, String collectionProperty)
{
    // Take the first result as the base value
    Object resultObject = null;
    MetaObject probe = null;
    Collection<Object> collection = null;
    for (Object object : valueObjects)
    {
        if (collection == null)
        {
            resultObject = object;
            probe = configuration.newMetaObject(resultObject);
            collection = (Collection<Object>) probe.getValue(collectionProperty);
        }
        else
        {
            Collection<?> addedValues = (Collection<Object>) probe.getValue(collectionProperty);
            collection.addAll(addedValues);
        }
    }
    // Done
    return resultObject;
}
 
Example 2
Source File: SqlHelper.java    From mybatis-generator-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * 通过命名空间方式获取sql
 * @param session
 * @param namespace
 * @param params
 * @return
 */
public static String getNamespaceSql(SqlSession session, String namespace, Object params) {
    Configuration configuration = session.getConfiguration();
    MappedStatement mappedStatement = configuration.getMappedStatement(namespace);
    TypeHandlerRegistry typeHandlerRegistry = mappedStatement.getConfiguration().getTypeHandlerRegistry();
    BoundSql boundSql = mappedStatement.getBoundSql(params);
    List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
    String sql = boundSql.getSql();
    if (parameterMappings != null) {
        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)) {
                    value = boundSql.getAdditionalParameter(propertyName);
                } else if (params == null) {
                    value = null;
                } else if (typeHandlerRegistry.hasTypeHandler(params.getClass())) {
                    value = params;
                } else {
                    MetaObject metaObject = configuration.newMetaObject(params);
                    value = metaObject.getValue(propertyName);
                }
                JdbcType jdbcType = parameterMapping.getJdbcType();
                if (value == null && jdbcType == null) jdbcType = configuration.getJdbcTypeForNull();
                sql = replaceParameter(sql, value, jdbcType, parameterMapping.getJavaType());
            }
        }
    }
    return sql;
}
 
Example 3
Source File: SQLHelper.java    From Shop-for-JavaWeb with 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 4
Source File: BoundSql.java    From mybaties with Apache License 2.0 5 votes vote down vote up
public BoundSql(Configuration configuration, String sql, List<ParameterMapping> parameterMappings, Object parameterObject) {
  this.sql = sql;
  this.parameterMappings = parameterMappings;
  this.parameterObject = parameterObject;
  this.additionalParameters = new HashMap<String, Object>();
  this.metaParameters = configuration.newMetaObject(additionalParameters);
}
 
Example 5
Source File: DynamicContext.java    From mybaties with Apache License 2.0 5 votes vote down vote up
public DynamicContext(Configuration configuration, Object parameterObject) {
//绝大多数调用的地方parameterObject为null
   if (parameterObject != null && !(parameterObject instanceof Map)) {
     //如果是map型
     MetaObject metaObject = configuration.newMetaObject(parameterObject);
     bindings = new ContextMap(metaObject);
   } else {
     bindings = new ContextMap(null);
   }
   bindings.put(PARAMETER_OBJECT_KEY, parameterObject);
   bindings.put(DATABASE_ID_KEY, configuration.getDatabaseId());
 }
 
Example 6
Source File: ResultLoaderMap.java    From mybaties with 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());
}
 
Example 7
Source File: BoundSql.java    From mybatis with Apache License 2.0 5 votes vote down vote up
public BoundSql(Configuration configuration, String sql, List<ParameterMapping> parameterMappings, Object parameterObject) {
  this.sql = sql;
  this.parameterMappings = parameterMappings;
  this.parameterObject = parameterObject;
  this.additionalParameters = new HashMap<String, Object>();
  this.metaParameters = configuration.newMetaObject(additionalParameters);
}
 
Example 8
Source File: DynamicContext.java    From mybatis with Apache License 2.0 5 votes vote down vote up
public DynamicContext(Configuration configuration, Object parameterObject) {
//绝大多数调用的地方parameterObject为null
   if (parameterObject != null && !(parameterObject instanceof Map)) {
     //如果是map型  ??  这句是 如果不是map型
     MetaObject metaObject = configuration.newMetaObject(parameterObject);
     bindings = new ContextMap(metaObject);
   } else {
     bindings = new ContextMap(null);
   }
   bindings.put(PARAMETER_OBJECT_KEY, parameterObject);
   bindings.put(DATABASE_ID_KEY, configuration.getDatabaseId());
 }
 
Example 9
Source File: ResultLoaderMap.java    From mybatis with 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());
}
 
Example 10
Source File: AutoMapperInterceptor.java    From mybatis.flying with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
private 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);
				}
				TypeHandler<Object> typeHandler = (TypeHandler<Object>) parameterMapping.getTypeHandler();
				if (typeHandler == null) {
					throw new AutoMapperException(
							new StringBuffer(AutoMapperExceptionEnum.NO_TYPE_HANDLER_SUITABLE.toString())
									.append(propertyName).append(" of statement ").append(mappedStatement.getId())
									.toString());
				}
				typeHandler.setParameter(ps, i + 1, value, parameterMapping.getJdbcType());
			}
		}
	}
}
 
Example 11
Source File: IdentityKeyGenerator.java    From mybatis-jpa with Apache License 2.0 4 votes vote down vote up
private void handleObject(MappedStatement ms, Statement stmt, Object parameter, Object idValue) {
  final String[] keyProperties = ms.getKeyProperties();
  final Configuration configuration = ms.getConfiguration();
  final MetaObject metaParam = configuration.newMetaObject(parameter);
  setValue(metaParam, keyProperties[0], idValue);
}
 
Example 12
Source File: PagePlugin.java    From cms with Apache License 2.0 4 votes vote down vote up
/**
 * org.apache.ibatis.executor.parameter. DefaultParameterHandler
 * 
 * @param ps
 * @param mappedStatement
 * @param boundSql
 * @param parameterObject
 * @throws SQLException
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
private 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);
				}
				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 13
Source File: MapperMethod.java    From mybaties with Apache License 2.0 4 votes vote down vote up
private <E> Object convertToDeclaredCollection(Configuration config, List<E> list) {
  Object collection = config.getObjectFactory().create(method.getReturnType());
  MetaObject metaObject = config.newMetaObject(collection);
  metaObject.addAll(list);
  return collection;
}
 
Example 14
Source File: SqlSourceBuilder.java    From mybaties with Apache License 2.0 4 votes vote down vote up
public ParameterMappingTokenHandler(Configuration configuration, Class<?> parameterType, Map<String, Object> additionalParameters) {
  super(configuration);
  this.parameterType = parameterType;
  this.metaParameters = configuration.newMetaObject(additionalParameters);
}
 
Example 15
Source File: MapperMethod.java    From mybatis with Apache License 2.0 4 votes vote down vote up
private <E> Object convertToDeclaredCollection(Configuration config, List<E> list) {
  Object collection = config.getObjectFactory().create(method.getReturnType());
  MetaObject metaObject = config.newMetaObject(collection);
  metaObject.addAll(list);
  return collection;
}
 
Example 16
Source File: SqlSourceBuilder.java    From mybatis with Apache License 2.0 4 votes vote down vote up
public ParameterMappingTokenHandler(Configuration configuration, Class<?> parameterType, Map<String, Object> additionalParameters) {
  super(configuration);
  this.parameterType = parameterType;
  this.metaParameters = configuration.newMetaObject(additionalParameters);
}