Java Code Examples for org.apache.ibatis.reflection.MetaObject

The following examples show how to use org.apache.ibatis.reflection.MetaObject. 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: FEBS-Cloud   Source File: DataPermissionInterceptor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Object intercept(Invocation invocation) throws Throwable {
    StatementHandler statementHandler = PluginUtils.realTarget(invocation.getTarget());
    MetaObject metaObject = SystemMetaObject.forObject(statementHandler);
    this.sqlParser(metaObject);
    MappedStatement mappedStatement = (MappedStatement) metaObject.getValue("delegate.mappedStatement");

    BoundSql boundSql = (BoundSql) metaObject.getValue("delegate.boundSql");
    Object paramObj = boundSql.getParameterObject();
    // 数据权限只针对查询语句
    if (SqlCommandType.SELECT == mappedStatement.getSqlCommandType()) {
        DataPermission dataPermission = getDataPermission(mappedStatement);
        if (shouldFilter(mappedStatement, dataPermission)) {
            String id = mappedStatement.getId();
            log.info("\n 数据权限过滤 method -> {}", id);
            String originSql = boundSql.getSql();
            String dataPermissionSql = dataPermissionSql(originSql, dataPermission);
            metaObject.setValue("delegate.boundSql.sql", dataPermissionSql);
            log.info("\n originSql -> {} \n dataPermissionSql: {}", originSql, dataPermissionSql);
        }
    }
    return invocation.proceed();
}
 
Example 2
Source Project: nano-framework   Source File: AbstractDataSourceFactory.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void setProperties(final Properties properties) {
    final Properties driverProperties = new Properties();
    final MetaObject metaDataSource = SystemMetaObject.forObject(dataSource);
    for (final Object key : properties.keySet()) {
        final String propertyName = (String) key;
        if (metaDataSource.hasSetter(propertyName)) {
            final String value = (String) properties.get(propertyName);
            /** 对没有设置值的属性跳过设置 */
            if (StringUtils.isNotEmpty(value) && value.startsWith("${") && value.endsWith("}")) {
                continue;
            }

            final Object convertedValue = convertValue(metaDataSource, propertyName, value);
            metaDataSource.setValue(propertyName, convertedValue);
        } else {
            throw new DataSourceException("Unknown DataSource property: " + propertyName);
        }
    }

    if (driverProperties.size() > 0) {
        metaDataSource.setValue("driverProperties", driverProperties);
    }
}
 
Example 3
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 4
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 5
Source Project: mybaties   Source File: DefaultResultSetHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void handleOutputParameters(CallableStatement cs) throws SQLException {
  final Object parameterObject = parameterHandler.getParameterObject();
  final MetaObject metaParam = configuration.newMetaObject(parameterObject);
  final List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
  //循环处理每个参数
  for (int i = 0; i < parameterMappings.size(); i++) {
    final ParameterMapping parameterMapping = parameterMappings.get(i);
    //只处理OUT|INOUT
    if (parameterMapping.getMode() == ParameterMode.OUT || parameterMapping.getMode() == ParameterMode.INOUT) {
      if (ResultSet.class.equals(parameterMapping.getJavaType())) {
        //如果是ResultSet型(游标)
        //#{result, jdbcType=CURSOR, mode=OUT, javaType=ResultSet, resultMap=userResultMap}
        //先用CallableStatement.getObject取得这个游标,作为参数传进去
        handleRefCursorOutputParameter((ResultSet) cs.getObject(i + 1), parameterMapping, metaParam);
      } else {
        //否则是普通型,核心就是CallableStatement.getXXX取得值
        final TypeHandler<?> typeHandler = parameterMapping.getTypeHandler();
        metaParam.setValue(parameterMapping.getProperty(), typeHandler.getResult(cs, i + 1));
      }
    }
  }
}
 
Example 6
Source Project: tk-mybatis   Source File: Example.java    License: 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 Project: Mybatis-PageHelper   Source File: PageObjectUtil.java    License: 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 8
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 9
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 10
Source Project: mybaties   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 11
Source Project: Mybatis-PageHelper   Source File: MySqlDialect.java    License: MIT License 6 votes vote down vote up
@Override
public Object processPageParameter(MappedStatement ms, Map<String, Object> paramMap, Page page, BoundSql boundSql, CacheKey pageKey) {
    paramMap.put(PAGEPARAMETER_FIRST, page.getStartRow());
    paramMap.put(PAGEPARAMETER_SECOND, page.getPageSize());
    //处理pageKey
    pageKey.update(page.getStartRow());
    pageKey.update(page.getPageSize());
    //处理参数配置
    if (boundSql.getParameterMappings() != null) {
        List<ParameterMapping> newParameterMappings = new ArrayList<ParameterMapping>(boundSql.getParameterMappings());
        if (page.getStartRow() == 0) {
            newParameterMappings.add(new ParameterMapping.Builder(ms.getConfiguration(), PAGEPARAMETER_SECOND, Integer.class).build());
        } else {
            newParameterMappings.add(new ParameterMapping.Builder(ms.getConfiguration(), PAGEPARAMETER_FIRST, Integer.class).build());
            newParameterMappings.add(new ParameterMapping.Builder(ms.getConfiguration(), PAGEPARAMETER_SECOND, Integer.class).build());
        }
        MetaObject metaObject = MetaObjectUtil.forObject(boundSql);
        metaObject.setValue("parameterMappings", newParameterMappings);
    }
    return paramMap;
}
 
Example 12
Source Project: Mapper   Source File: Example.java    License: 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) {
    if(param == null){
        return (Criteria) this;
    }
    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) {
                andEqualTo(property, value);
            }
        }
    }
    return (Criteria) this;
}
 
Example 13
Source Project: mybaties   Source File: BeanWrapper.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean hasGetter(String name) {
  PropertyTokenizer prop = new PropertyTokenizer(name);
  if (prop.hasNext()) {
    if (metaClass.hasGetter(prop.getIndexedName())) {
      MetaObject metaValue = metaObject.metaObjectForProperty(prop.getIndexedName());
      if (metaValue == SystemMetaObject.NULL_META_OBJECT) {
        return metaClass.hasGetter(name);
      } else {
        return metaValue.hasGetter(prop.getChildren());
      }
    } else {
      return false;
    }
  } else {
    return metaClass.hasGetter(name);
  }
}
 
Example 14
Source Project: mybatis-boost   Source File: UpdateEnhancement.java    License: MIT License 6 votes vote down vote up
@Override
public void replace(Connection connection, MetaObject metaObject, MappedStatement mappedStatement, BoundSql boundSql) {
    String sql = boundSql.getSql();
    if (mappedStatement.getSqlCommandType() == SqlCommandType.UPDATE &&
            sql.toUpperCase().startsWith("UPDATE SET ")) {
        String[] split = splitSql(sql); // split[0] = columns, split[1] = conditions(if there were)
        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(split[0], entityType, mapUnderscoreToCamelCase);
        List<String> conditionProperties = getConditionProperties(entityType, boundSql.getParameterMappings());
        propertiesAndColumns.first().removeAll(conditionProperties);
        propertiesAndColumns.second().removeAll(conditionProperties.stream()
                .map(it -> SqlUtils.normalizeColumn(it, mapUnderscoreToCamelCase)).collect(Collectors.toList()));

        metaObject.setValue("delegate.boundSql.sql",
                buildSQL(sql, entityType, propertiesAndColumns.second(), split));
        metaObject.setValue("delegate.boundSql.parameterMappings",
                getParameterMappings(metaObject, boundSql, propertiesAndColumns.first()));
    }
}
 
Example 15
Source Project: mybatis-boost   Source File: MapperSqlProvider.java    License: MIT License 6 votes vote down vote up
@Override
public void replace(Connection connection, MetaObject metaObject, MappedStatement mappedStatement, BoundSql boundSql) {
    if (Objects.equals(boundSql.getSql(), SqlProvider.MYBATIS_BOOST)) {
        Class<?> providerType = (Class<?>)
                MyBatisUtils.getMetaObject(mappedStatement.getSqlSource()).getValue("providerType");
        SqlProvider provider = providerMap.get(providerType);
        if (provider == null) {
            synchronized (providerType) {
                provider = providerMap.computeIfAbsent(providerType, UncheckedFunction.of(k -> {
                    SqlProvider p = (SqlProvider) providerType.newInstance();
                    if (p instanceof ConfigurationAware) {
                        ((ConfigurationAware) p).setConfiguration(configuration);
                    }
                    return p;
                }));
            }
        }
        if (provider != null) {
            provider.replace(connection, metaObject, mappedStatement, boundSql);
        }
    }
}
 
Example 16
Source Project: mybatis   Source File: BaseExecutor.java    License: Apache License 2.0 6 votes vote down vote up
private void handleLocallyCachedOutputParameters(MappedStatement ms, CacheKey key, Object parameter, BoundSql boundSql) {
  //处理存储过程的OUT参数
  if (ms.getStatementType() == StatementType.CALLABLE) {
    final Object cachedParameter = localOutputParameterCache.getObject(key);
    if (cachedParameter != null && parameter != null) {
      final MetaObject metaCachedParameter = configuration.newMetaObject(cachedParameter);
      final MetaObject metaParameter = configuration.newMetaObject(parameter);
      for (ParameterMapping parameterMapping : boundSql.getParameterMappings()) {
        if (parameterMapping.getMode() != ParameterMode.IN) {
          final String parameterName = parameterMapping.getProperty();
          final Object cachedValue = metaCachedParameter.getValue(parameterName);
          metaParameter.setValue(parameterName, cachedValue);
        }
      }
    }
  }
}
 
Example 17
Source Project: mybatis   Source File: DefaultResultSetHandler.java    License: Apache License 2.0 5 votes vote down vote up
private boolean applyAutomaticMappings(ResultSetWrapper rsw, ResultMap resultMap, MetaObject metaObject, String columnPrefix) throws SQLException {
  final List<String> unmappedColumnNames = rsw.getUnmappedColumnNames(resultMap, columnPrefix);
  boolean foundValues = false;
  for (String columnName : unmappedColumnNames) {
    String propertyName = columnName;
    if (columnPrefix != null && !columnPrefix.isEmpty()) {
      // When columnPrefix is specified,
      // ignore columns without the prefix.
      if (columnName.toUpperCase(Locale.ENGLISH).startsWith(columnPrefix)) {
        propertyName = columnName.substring(columnPrefix.length());
      } else {
        continue;
      }
    }
    final String property = metaObject.findProperty(propertyName, configuration.isMapUnderscoreToCamelCase());
    if (property != null && metaObject.hasSetter(property)) {
      final Class<?> propertyType = metaObject.getSetterType(property);
      if (typeHandlerRegistry.hasTypeHandler(propertyType)) {
        final TypeHandler<?> typeHandler = rsw.getTypeHandler(propertyType, columnName);
        //巧妙的用TypeHandler取得结果
        final Object value = typeHandler.getResult(rsw.getResultSet(), columnName);
        // issue #377, call setter on nulls
        if (value != null || configuration.isCallSettersOnNulls()) {
          if (value != null || !propertyType.isPrimitive()) {
            //然后巧妙的用反射来设置到对象
            metaObject.setValue(property, value);
          }
          foundValues = true;
        }
      }
    }
  }
  return foundValues;
}
 
Example 18
Source Project: mybaties   Source File: DynamicContext.java    License: 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 19
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 20
Source Project: Mybatis-PageHelper   Source File: AbstractHelperDialect.java    License: MIT License 5 votes vote down vote up
protected void handleParameter(BoundSql boundSql, MappedStatement ms){
    if (boundSql.getParameterMappings() != null) {
        List<ParameterMapping> newParameterMappings = new ArrayList<ParameterMapping>(boundSql.getParameterMappings());
        newParameterMappings.add(new ParameterMapping.Builder(ms.getConfiguration(), PAGEPARAMETER_FIRST, Integer.class).build());
        newParameterMappings.add(new ParameterMapping.Builder(ms.getConfiguration(), PAGEPARAMETER_SECOND, Integer.class).build());
        MetaObject metaObject = MetaObjectUtil.forObject(boundSql);
        metaObject.setValue("parameterMappings", newParameterMappings);
    }
}
 
Example 21
Source Project: Mapper   Source File: MetaObjectUtil.java    License: MIT License 5 votes vote down vote up
public static MetaObject forObject(Object object) {
    try {
        return (MetaObject) method.invoke(null, object);
    } catch (Exception e) {
        throw new MapperException(e);
    }
}
 
Example 22
@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 23
Source Project: mybaties   Source File: DefaultMapResultHandler.java    License: 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 24
/**
 * 插入填充,字段为空自动填充
 */
@Override
public void insertFill(MetaObject metaObject) {
    Object createTime = getFieldValByName(autoFillProperties.getCreateTimeField(), metaObject);
    Object updateTime = getFieldValByName(autoFillProperties.getUpdateTimeField(), metaObject);
    if (createTime == null || updateTime == null) {
        Date date = new Date();
        if (createTime == null) {
            setFieldValByName(autoFillProperties.getCreateTimeField(), date, metaObject);
        }
        if (updateTime == null) {
            setFieldValByName(autoFillProperties.getUpdateTimeField(), date, metaObject);
        }
    }
}
 
Example 25
Source Project: mybaties   Source File: DefaultParameterHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void setParameters(PreparedStatement ps) throws SQLException {
  ErrorContext.instance().activity("setting parameters").object(mappedStatement.getParameterMap().getId());
  List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
  if (parameterMappings != null) {
    //循环设参数
    for (int i = 0; i < parameterMappings.size(); i++) {
      ParameterMapping parameterMapping = parameterMappings.get(i);
      if (parameterMapping.getMode() != ParameterMode.OUT) {
        //如果不是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) {
          //若参数为null,直接设null
          value = null;
        } else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
          //若参数有相应的TypeHandler,直接设object
          value = parameterObject;
        } else {
          //除此以外,MetaObject.getValue反射取得值设进去
          MetaObject metaObject = configuration.newMetaObject(parameterObject);
          value = metaObject.getValue(propertyName);
        }
        TypeHandler typeHandler = parameterMapping.getTypeHandler();
        JdbcType jdbcType = parameterMapping.getJdbcType();
        if (value == null && jdbcType == null) {
          //不同类型的set方法不同,所以委派给子类的setParameter方法
          jdbcType = configuration.getJdbcTypeForNull();
        }
        typeHandler.setParameter(ps, i + 1, value, jdbcType);
      }
    }
  }
}
 
Example 26
Source Project: mybaties   Source File: BaseExecutor.java    License: Apache License 2.0 5 votes vote down vote up
public DeferredLoad(MetaObject resultObject,
                    String property,
                    CacheKey key,
                    PerpetualCache localCache,
                    Configuration configuration,
                    Class<?> targetType) {
  this.resultObject = resultObject;
  this.property = property;
  this.key = key;
  this.localCache = localCache;
  this.objectFactory = configuration.getObjectFactory();
  this.resultExtractor = new ResultExtractor(configuration, objectFactory);
  this.targetType = targetType;
}
 
Example 27
Source Project: mybaties   Source File: DefaultResultSetHandler.java    License: Apache License 2.0 5 votes vote down vote up
private void handleRefCursorOutputParameter(ResultSet rs, ParameterMapping parameterMapping, MetaObject metaParam) throws SQLException {
  try {
    final String resultMapId = parameterMapping.getResultMapId();
    final ResultMap resultMap = configuration.getResultMap(resultMapId);
    final DefaultResultHandler resultHandler = new DefaultResultHandler(objectFactory);
    final ResultSetWrapper rsw = new ResultSetWrapper(rs, configuration);
    //里面就和一般ResultSet处理没两样了
    handleRowValues(rsw, resultMap, resultHandler, new RowBounds(), null);
    metaParam.setValue(parameterMapping.getProperty(), resultHandler.getResultList());
  } finally {
    // issue #228 (close resultsets)
    closeResultSet(rs);
  }
}
 
Example 28
Source Project: code   Source File: DataScopeInterceptor.java    License: 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 29
Source Project: code   Source File: DataScopeInterceptor.java    License: Apache License 2.0 5 votes vote down vote up
private static Object realTarget(Object target) {
    if (Proxy.isProxyClass(target.getClass())) {
        MetaObject metaObject = SystemMetaObject.forObject(target);
        return realTarget(metaObject.getValue("h.target"));
    } else {
        return target;
    }
}
 
Example 30
Source Project: ruoyiplus   Source File: CustomMetaObjectHandler.java    License: MIT License 5 votes vote down vote up
@Override
public void insertFill(MetaObject metaObject) {
    Object fieldValue = getFieldValByName(COMMON_FIELD_CREATEDATE, metaObject);
    if (fieldValue == null) {
        setFieldValByName(COMMON_FIELD_CREATEDATE, new Date(), metaObject);
    }
}