Java Code Examples for org.apache.ibatis.reflection.MetaObject#getValue()

The following examples show how to use org.apache.ibatis.reflection.MetaObject#getValue() . 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: Example.java    From Mapper with MIT License 6 votes vote down vote up
/**
 * 将此对象的不为空的字段参数作为相等查询条件
 *
 * @param param 参数对象
 * @author Bob {@link}[email protected]
 * @Date 2015年7月17日 下午12:48:08
 */
public Criteria orEqualTo(Object param) {
    MetaObject metaObject = MetaObjectUtil.forObject(param);
    String[] properties = metaObject.getGetterNames();
    for (String property : properties) {
        //属性和列对应Map中有此属性
        if (propertyMap.get(property) != null) {
            Object value = metaObject.getValue(property);
            //属性值不为空
            if (value != null) {
                orEqualTo(property, value);
            }
        }
    }
    return (Criteria) this;
}
 
Example 2
Source File: DefaultResultSetHandler.java    From mybaties with 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 File: ListParameterEnhancement.java    From mybatis-boost with MIT License 6 votes vote down vote up
private Map<Integer, List<?>> getLists(Object parameterObject, List<ParameterMapping> parameterMappings) {
    if (parameterMappings.isEmpty()) {
        return Collections.emptyMap();
    } else {
        Map<Integer, List<?>> listMap = new HashMap<>();
        MetaObject parameterMetaObject = MyBatisUtils.getMetaObject(parameterObject);
        for (int i = 0; i < parameterMappings.size(); i++) {
            try {
                Object property = parameterMetaObject.getValue(parameterMappings.get(i).getProperty());
                if (property instanceof List) {
                    listMap.put(i, (List<?>) property);
                }
            } catch (Exception ignored) {
                return Collections.emptyMap();
            }
        }
        return listMap;
    }
}
 
Example 4
Source File: PageObjectUtil.java    From Mybatis-PageHelper with MIT License 6 votes vote down vote up
/**
 * 从对象中取参数
 *
 * @param paramsObject
 * @param paramName
 * @param required
 * @return
 */
protected static Object getParamValue(MetaObject paramsObject, String paramName, boolean required) {
    Object value = null;
    if (paramsObject.hasGetter(PARAMS.get(paramName))) {
        value = paramsObject.getValue(PARAMS.get(paramName));
    }
    if (value != null && value.getClass().isArray()) {
        Object[] values = (Object[]) value;
        if (values.length == 0) {
            value = null;
        } else {
            value = values[0];
        }
    }
    if (required && value == null) {
        throw new PageException("分页查询缺少必要的参数:" + PARAMS.get(paramName));
    }
    return value;
}
 
Example 5
Source File: PageResultInterceptor.java    From joyqueue with Apache License 2.0 6 votes vote down vote up
@Override
public Object intercept(Invocation invocation) throws Throwable {
    // 目标对象转换
    ResultSetHandler resultSetHandler = (ResultSetHandler) invocation.getTarget();

    // 获取MappedStatement,Configuration对象
    MetaObject metaObject =
            MetaObject.forObject(resultSetHandler, new DefaultObjectFactory(), new DefaultObjectWrapperFactory(), new DefaultReflectorFactory());
    MappedStatement mappedStatement = (MappedStatement) metaObject.getValue("mappedStatement");
    String statement = mappedStatement.getId();
    if (!isPageSql(statement,metaObject.getValue("boundSql.parameterObject"))) {
        return invocation.proceed();
    }

    // 获取分页参数
    QPageQuery pageQuery = (QPageQuery) metaObject.getValue("boundSql.parameterObject");

    List<PageResult> result = new ArrayList<PageResult>(1);
    PageResult page = new PageResult();
    page.setPagination(pageQuery.getPagination());
    page.setResult((List) invocation.proceed());
    result.add(page);

    return result;
}
 
Example 6
Source File: Example.java    From tk-mybatis with MIT License 6 votes vote down vote up
/**
 * 将此对象的不为空的字段参数作为相等查询条件
 *
 * @param param 参数对象
 * @author Bob {@link}[email protected]
 * @Date 2015年7月17日 下午12:48:08
 */
public Criteria andEqualTo(Object param) {
    MetaObject metaObject = SystemMetaObject.forObject(param);
    String[] properties = metaObject.getGetterNames();
    for (String property : properties) {
        //属性和列对应Map中有此属性
        if (propertyMap.get(property) != null) {
            Object value = metaObject.getValue(property);
            //属性值不为空
            if (value != null) {
                andEqualTo(property, value);
            }
        }
    }
    return (Criteria) this;
}
 
Example 7
Source File: DefaultMapResultHandler.java    From mybatis with Apache License 2.0 5 votes vote down vote up
@Override
public void handleResult(ResultContext context) {
  // TODO is that assignment always true?
  //得到一条记录
  //这边黄色警告没法去掉了?因为返回Object型
  final V value = (V) context.getResultObject();
  //MetaObject.forObject,包装一下记录
  //MetaObject是用反射来包装各种类型
  final MetaObject mo = MetaObject.forObject(value, objectFactory, objectWrapperFactory);
  // TODO is that assignment always true?
  final K key = (K) mo.getValue(mapKey);
  mappedResults.put(key, value);
  //这个类主要目的是把得到的List转为Map
}
 
Example 8
Source File: DataScopeInterceptor.java    From code with Apache License 2.0 5 votes vote down vote up
@Override
public Object intercept(Invocation invocation) throws Throwable {
    StatementHandler statementHandler = (StatementHandler) realTarget(invocation.getTarget());
    MetaObject metaStatementHandler = SystemMetaObject.forObject(statementHandler);
    MappedStatement mappedStatement = (MappedStatement) metaStatementHandler.getValue("delegate.mappedStatement");

    if (!SqlCommandType.SELECT.equals(mappedStatement.getSqlCommandType())) {
        return invocation.proceed();
    }

    BoundSql boundSql = (BoundSql) metaStatementHandler.getValue("delegate.boundSql");
    String originalSql = boundSql.getSql();
    Object parameterObject = boundSql.getParameterObject();

    //查找参数中包含DataScope类型的参数
    DataScope dataScope = findDataScopeObject(parameterObject);

    if (dataScope == null) {
        return invocation.proceed();
    } else {
        String scopeName = dataScope.getScopeName();
        List<Integer> deptIds = dataScope.getDeptIds();
        String join = join(deptIds, ",");
        originalSql = "select * from (" + originalSql + ") temp_data_scope where temp_data_scope." + scopeName + " in (" + join + ")";

        metaStatementHandler.setValue("delegate.boundSql.sql", originalSql);
        return invocation.proceed();
    }
}
 
Example 9
Source File: DataScopeInterceptor.java    From MeetingFilm with Apache License 2.0 5 votes vote down vote up
@Override
public Object intercept(Invocation invocation) throws Throwable {
    StatementHandler statementHandler = (StatementHandler) PluginUtils.realTarget(invocation.getTarget());
    MetaObject metaStatementHandler = SystemMetaObject.forObject(statementHandler);
    MappedStatement mappedStatement = (MappedStatement) metaStatementHandler.getValue("delegate.mappedStatement");

    if (!SqlCommandType.SELECT.equals(mappedStatement.getSqlCommandType())) {
        return invocation.proceed();
    }

    BoundSql boundSql = (BoundSql) metaStatementHandler.getValue("delegate.boundSql");
    String originalSql = boundSql.getSql();
    Object parameterObject = boundSql.getParameterObject();

    //查找参数中包含DataScope类型的参数
    DataScope dataScope = findDataScopeObject(parameterObject);

    if (dataScope == null) {
        return invocation.proceed();
    } else {
        String scopeName = dataScope.getScopeName();
        List<Integer> deptIds = dataScope.getDeptIds();
        String join = CollectionKit.join(deptIds, ",");
        originalSql = "select * from (" + originalSql + ") temp_data_scope where temp_data_scope." + scopeName + " in (" + join + ")";
        metaStatementHandler.setValue("delegate.boundSql.sql", originalSql);
        return invocation.proceed();
    }
}
 
Example 10
Source File: BaseExecutor.java    From mybatis with Apache License 2.0 5 votes vote down vote up
@Override
public CacheKey createCacheKey(MappedStatement ms, Object parameterObject, RowBounds rowBounds, BoundSql boundSql) {
  if (closed) {
    throw new ExecutorException("Executor was closed.");
  }
  CacheKey cacheKey = new CacheKey();
  //MyBatis 对于其 Key 的生成采取规则为:[mappedStementId + offset + limit + SQL + queryParams + environment]生成一个哈希码
  cacheKey.update(ms.getId());
  cacheKey.update(Integer.valueOf(rowBounds.getOffset()));
  cacheKey.update(Integer.valueOf(rowBounds.getLimit()));
  cacheKey.update(boundSql.getSql());
  List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
  TypeHandlerRegistry typeHandlerRegistry = ms.getConfiguration().getTypeHandlerRegistry();
  // mimic DefaultParameterHandler logic
  //模仿DefaultParameterHandler的逻辑,不再重复,请参考DefaultParameterHandler
  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 (parameterObject == null) {
        value = null;
      } else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
        value = parameterObject;
      } else {
        MetaObject metaObject = configuration.newMetaObject(parameterObject);
        value = metaObject.getValue(propertyName);
      }
      cacheKey.update(value);
    }
  }
  if (configuration.getEnvironment() != null) {
    // issue #176
    cacheKey.update(configuration.getEnvironment().getId());
  }
  return cacheKey;
}
 
Example 11
Source File: DefaultMapResultHandler.java    From mybaties with Apache License 2.0 5 votes vote down vote up
@Override
public void handleResult(ResultContext context) {
  // TODO is that assignment always true?
  //得到一条记录
  //这边黄色警告没法去掉了?因为返回Object型
  final V value = (V) context.getResultObject();
  //MetaObject.forObject,包装一下记录
  //MetaObject是用反射来包装各种类型
  final MetaObject mo = MetaObject.forObject(value, objectFactory, objectWrapperFactory);
  // TODO is that assignment always true?
  final K key = (K) mo.getValue(mapKey);
  mappedResults.put(key, value);
  //这个类主要目的是把得到的List转为Map
}
 
Example 12
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 13
Source File: DataScopeInterceptor.java    From smaker with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public Object intercept(Invocation invocation) throws Throwable {
	StatementHandler statementHandler = (StatementHandler) PluginUtils.realTarget(invocation.getTarget());
	MetaObject metaObject = SystemMetaObject.forObject(statementHandler);
	this.sqlParser(metaObject);
	// 先判断是不是SELECT操作
	MappedStatement mappedStatement = (MappedStatement) metaObject.getValue("delegate.mappedStatement");
	if (!SqlCommandType.SELECT.equals(mappedStatement.getSqlCommandType())) {
		return invocation.proceed();
	}

	BoundSql boundSql = (BoundSql) metaObject.getValue("delegate.boundSql");
	String originalSql = boundSql.getSql();
	Object parameterObject = boundSql.getParameterObject();

	//查找参数中包含DataScope类型的参数
	DataScope dataScope = findDataScopeObject(parameterObject);

	if (dataScope == null) {
		return invocation.proceed();
	} else {
		String scopeName = dataScope.getScopeName();
		List<Integer> deptIds = dataScope.getDeptIds();
		if (StrUtil.isNotBlank(scopeName) && CollectionUtil.isNotEmpty(deptIds)) {
			String join = CollectionUtil.join(deptIds, ",");
			originalSql = "select * from (" + originalSql + ") temp_data_scope where temp_data_scope." + scopeName + " in (" + join + ")";
			metaObject.setValue("delegate.boundSql.sql", originalSql);
		}
		return invocation.proceed();
	}
}
 
Example 14
Source File: DataScopeInterceptor.java    From pig with MIT License 5 votes vote down vote up
@Override
public Object intercept(Invocation invocation) throws Throwable {
    StatementHandler statementHandler = (StatementHandler) PluginUtils.realTarget(invocation.getTarget());
    MetaObject metaObject = SystemMetaObject.forObject(statementHandler);
    this.sqlParser(metaObject);
    // 先判断是不是SELECT操作
    MappedStatement mappedStatement = (MappedStatement) metaObject.getValue("delegate.mappedStatement");
    if (!SqlCommandType.SELECT.equals(mappedStatement.getSqlCommandType())) {
        return invocation.proceed();
    }

    BoundSql boundSql = (BoundSql) metaObject.getValue("delegate.boundSql");
    String originalSql = boundSql.getSql();
    Object parameterObject = boundSql.getParameterObject();

    //查找参数中包含DataScope类型的参数
    DataScope dataScope = findDataScopeObject(parameterObject);

    if (dataScope == null) {
        return invocation.proceed();
    } else {
        String scopeName = dataScope.getScopeName();
        List<Integer> deptIds = dataScope.getDeptIds();
        if(StrUtil.isNotBlank(scopeName) && CollectionUtil.isNotEmpty(deptIds)){
            String join = CollectionUtil.join(deptIds, ",");
            originalSql = "select * from (" + originalSql + ") temp_data_scope where temp_data_scope." + scopeName + " in (" + join + ")";
            metaObject.setValue("delegate.boundSql.sql", originalSql);
        }
        return invocation.proceed();
    }
}
 
Example 15
Source File: InsertEnhancement.java    From mybatis-boost with MIT License 5 votes vote down vote up
@Override
public void replace(Connection connection, MetaObject metaObject, MappedStatement mappedStatement, BoundSql boundSql) {
    String sql = boundSql.getSql();
    String sqlUpperCase = sql.toUpperCase();
    if (mappedStatement.getSqlCommandType() == SqlCommandType.INSERT &&
            !sqlUpperCase.startsWith("INSERT INTO ") && sqlUpperCase.startsWith("INSERT ")) {
        Matcher matcher = PATTERN_LITERAL_COLUMNS.matcher(sql = sql.substring(7));
        if (!matcher.find()) {
            throw new IllegalStateException("Found INSERT statement but no column is specified");
        }

        String literalColumns = matcher.group();
        Class<?> entityType = MapperUtils.getEntityTypeFromMapper
                (mappedStatement.getId().substring(0, mappedStatement.getId().lastIndexOf('.')));
        boolean mapUnderscoreToCamelCase = (boolean)
                metaObject.getValue("delegate.configuration.mapUnderscoreToCamelCase");
        BinaryTuple<List<String>, List<String>> propertiesAndColumns =
                SqlUtils.getPropertiesAndColumnsFromLiteralColumns(literalColumns, entityType, mapUnderscoreToCamelCase);

        List<?> entities = boundSql.getParameterObject() instanceof Map ?
                (List<?>) ((Map) boundSql.getParameterObject()).get("param1") :
                Collections.singletonList(Objects.requireNonNull(boundSql.getParameterObject(),
                        "ParameterObject mustn't be null"));
        if (entities.isEmpty()) {
            throw new IllegalArgumentException("Can't insert empty list");
        } else {
            String additionalStatement = sql.substring(literalColumns.length());
            org.apache.ibatis.session.Configuration configuration =
                    (org.apache.ibatis.session.Configuration) metaObject.getValue("delegate.configuration");
            Object parameterObject = buildParameterObject(entities);
            metaObject.setValue("delegate.boundSql.sql",
                    buildSql(entityType, propertiesAndColumns.second(), entities.size(), additionalStatement));
            metaObject.setValue("delegate.boundSql.parameterMappings",
                    MyBatisUtils.getListParameterMappings(configuration, propertiesAndColumns.first(), entities.size()));
            metaObject.setValue("delegate.boundSql.parameterObject", parameterObject);
            MyBatisUtils.getMetaObject(metaObject.getValue("delegate.parameterHandler"))
                    .setValue("parameterObject", parameterObject);
        }
    }
}
 
Example 16
Source File: CustomMybatisPlusParameterHandler.java    From sqlhelper with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static Object populateKeys(MetaObjectHandler metaObjectHandler, TableInfo tableInfo, MappedStatement ms, Object parameterObject, boolean isInsert) {
    if (null == tableInfo) {
        return parameterObject;
    } else {
        MetaObject metaObject = ms.getConfiguration().newMetaObject(parameterObject);
        if (isInsert && !StringUtils.isEmpty(tableInfo.getKeyProperty()) && null != tableInfo.getIdType() && tableInfo.getIdType().getKey() >= 3) {
            Object idValue = metaObject.getValue(tableInfo.getKeyProperty());
            if (StringUtils.checkValNull(idValue)) {
                if (tableInfo.getIdType() == IdType.ID_WORKER) {
                    metaObject.setValue(tableInfo.getKeyProperty(), IdWorker.getId());
                } else if (tableInfo.getIdType() == IdType.ID_WORKER_STR) {
                    metaObject.setValue(tableInfo.getKeyProperty(), IdWorker.getIdStr());
                } else if (tableInfo.getIdType() == IdType.UUID) {
                    metaObject.setValue(tableInfo.getKeyProperty(), IdWorker.get32UUID());
                }
            }
        }

        if (metaObjectHandler != null) {
            if (isInsert && metaObjectHandler.openInsertFill()) {
                metaObjectHandler.insertFill(metaObject);
            } else if (!isInsert) {
                metaObjectHandler.updateFill(metaObject);
            }
        }

        return metaObject.getOriginalObject();
    }
}
 
Example 17
Source File: Delete.java    From mybatis-boost with MIT License 5 votes vote down vote up
@Override
public void replace(Connection connection, MetaObject metaObject, MappedStatement mappedStatement, BoundSql boundSql) {
    Class<?> entityType = MapperUtils.getEntityTypeFromMapper
            (mappedStatement.getId().substring(0, mappedStatement.getId().lastIndexOf('.')));
    StringBuilder sqlBuilder = new StringBuilder();
    sqlBuilder.append("DELETE FROM ").append(EntityUtils.getTableName(entityType, configuration.getNameAdaptor()));

    Map<?, ?> parameterMap = (Map<?, ?>) boundSql.getParameterObject();
    Object entity = parameterMap.get("param1");
    List<String> properties;
    String[] conditionalProperties = (String[]) parameterMap.get("param2");
    if (conditionalProperties.length == 0) {
        properties = EntityUtils.getProperties(entity, true);
    } else {
        properties = Arrays.stream(conditionalProperties).map(PropertyUtils::normalizeProperty).collect(Collectors.toList());
    }

    if (!properties.isEmpty()) {
        boolean mapUnderscoreToCamelCase = (boolean)
                metaObject.getValue("delegate.configuration.mapUnderscoreToCamelCase");
        List<String> columns = properties.stream()
                .map(it -> SqlUtils.normalizeColumn(it, mapUnderscoreToCamelCase)).collect(Collectors.toList());
        SqlUtils.appendWhere(sqlBuilder, columns.stream());
    }

    List<ParameterMapping> parameterMappings = MyBatisUtils.getParameterMappings
            ((org.apache.ibatis.session.Configuration)
                    metaObject.getValue("delegate.configuration"), properties);
    MyBatisUtils.getMetaObject(metaObject.getValue("delegate.parameterHandler"))
            .setValue("parameterObject", entity);
    metaObject.setValue("delegate.boundSql.parameterObject", entity);
    metaObject.setValue("delegate.boundSql.parameterMappings", parameterMappings);
    metaObject.setValue("delegate.boundSql.sql", sqlBuilder.toString());
}
 
Example 18
Source File: MetaObjectAssistant.java    From Aooms with Apache License 2.0 4 votes vote down vote up
public static Object getParameterObject(MetaObject metaObject) {
    Object parameterObject = metaObject.getValue("delegate.boundSql.parameterObject");
    return parameterObject;
}
 
Example 19
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 20
Source File: Update.java    From mybatis-boost with MIT License 4 votes vote down vote up
@Override
public void replace(Connection connection, MetaObject metaObject, MappedStatement mappedStatement, BoundSql boundSql) {
    Class<?> entityType = MapperUtils.getEntityTypeFromMapper
            (mappedStatement.getId().substring(0, mappedStatement.getId().lastIndexOf('.')));
    StringBuilder sqlBuilder = new StringBuilder();
    sqlBuilder.append("UPDATE ").append(EntityUtils.getTableName(entityType, configuration.getNameAdaptor()));

    boolean partial = mappedStatement.getId().contains("Partial");
    boolean selective = mappedStatement.getId().contains("Selective");

    Map<?, ?> parameterMap = (Map<?, ?>) boundSql.getParameterObject();
    Object entity = parameterMap.get("param1");
    List<String> properties;
    String[] conditionalProperties;
    if (!partial) {
        properties = EntityUtils.getProperties(entity, selective);
        conditionalProperties = (String[]) parameterMap.get("param2");
    } else {
        String[] candidateProperties = (String[]) parameterMap.get("param2");
        properties = PropertyUtils.buildPropertiesWithCandidates(candidateProperties, entity, selective);
        conditionalProperties = (String[]) parameterMap.get("param3");
    }
    if (conditionalProperties.length == 0) {
        conditionalProperties = new String[]{EntityUtils.getIdProperty(entityType)};
    }
    PropertyUtils.rebuildPropertiesWithConditions(properties, entityType, conditionalProperties);

    if (!properties.isEmpty()) {
        boolean mapUnderscoreToCamelCase = (boolean)
                metaObject.getValue("delegate.configuration.mapUnderscoreToCamelCase");
        List<String> columns = properties.stream()
                .map(it -> SqlUtils.normalizeColumn(it, mapUnderscoreToCamelCase)).collect(Collectors.toList());
        sqlBuilder.append(" SET ");
        columns.stream().limit(columns.size() - conditionalProperties.length)
                .forEach(c -> sqlBuilder.append(c).append(" = ?, "));
        sqlBuilder.setLength(sqlBuilder.length() - 2);
        SqlUtils.appendWhere(sqlBuilder, columns.stream().skip(columns.size() - conditionalProperties.length));
    }

    List<ParameterMapping> parameterMappings = MyBatisUtils.getParameterMappings
            ((org.apache.ibatis.session.Configuration)
                    metaObject.getValue("delegate.configuration"), properties);
    MyBatisUtils.getMetaObject(metaObject.getValue("delegate.parameterHandler"))
            .setValue("parameterObject", entity);
    metaObject.setValue("delegate.boundSql.parameterObject", entity);
    metaObject.setValue("delegate.boundSql.parameterMappings", parameterMappings);
    metaObject.setValue("delegate.boundSql.sql", sqlBuilder.toString());
}