org.apache.ibatis.reflection.MetaObject Java Examples

The following examples show how to use org.apache.ibatis.reflection.MetaObject. 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: BaseExecutor.java    From mybatis with 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 #2
Source File: SelectKeyGenerator.java    From mybatis with 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 #3
Source File: AbstractDataSourceFactory.java    From nano-framework with 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 #4
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 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 #5
Source File: MySqlDialect.java    From Mybatis-PageHelper with 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 #6
Source File: BeanWrapper.java    From mybaties with 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 #7
Source File: DefaultResultSetHandler.java    From mybaties with 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 #8
Source File: SelectKeyGenerator.java    From Mapper with 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 #9
Source File: DataPermissionInterceptor.java    From FEBS-Cloud with 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 #10
Source File: UpdateEnhancement.java    From mybatis-boost with 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 #11
Source File: DefaultResultSetHandler.java    From mybaties with 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 #12
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 #13
Source File: MapperSqlProvider.java    From mybatis-boost with 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 #14
Source File: SelectKeyGenerator.java    From tk-mybatis with 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 #15
Source File: DefaultResultSetHandler.java    From mybatis 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 #16
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 #17
Source File: MyMetaObjectHandler.java    From springboot-restful-starter with MIT License 5 votes vote down vote up
/**
 * 自动插入创建时间到create_time字段
 */
@Override
public void insertFill(MetaObject metaObject) {
    // 默认插入的时间戳对应数据库的int类型
    // 若要使用精确到秒级的时间戳请将getCurrentUnixTimestamp()改成System.currentTimeMillis()并在数据库中设置long类型的create_time字段
    this.setFieldValByName("createTime", getCurrentUnixTimestamp(), metaObject);
}
 
Example #18
Source File: MyBatisUtils.java    From mybatis-boost with MIT License 5 votes vote down vote up
public static MetaObject getMetaObject(Object target) {
    MetaObject metaObject;
    while ((metaObject = forObject(target)).hasGetter("h")) {
        target = metaObject.getValue("h.target");
    }
    return metaObject;
}
 
Example #19
Source File: PostgreSQL.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) {
    metaObject.setValue("delegate.boundSql.sql",
            SqlUtils.appendLimitOffset(boundSql.getSql(), (RowBounds) metaObject.getValue("delegate.rowBounds")));
    metaObject.setValue("delegate.rowBounds", RowBounds.DEFAULT);
    MyBatisUtils.getMetaObject(metaObject.getValue("delegate.resultSetHandler"))
            .setValue("rowBounds", RowBounds.DEFAULT);
}
 
Example #20
Source File: CacheBuilder.java    From mybaties with Apache License 2.0 5 votes vote down vote up
private void setCacheProperties(Cache cache) {
  if (properties != null) {
    MetaObject metaCache = SystemMetaObject.forObject(cache);
    //用反射设置额外的property属性
    for (Map.Entry<Object, Object> entry : properties.entrySet()) {
      String name = (String) entry.getKey();
      String value = (String) entry.getValue();
      if (metaCache.hasSetter(name)) {
        Class<?> type = metaCache.getSetterType(name);
        //下面就是各种基本类型的判断了,味同嚼蜡但是又不得不写
        if (String.class == type) {
          metaCache.setValue(name, value);
        } else if (int.class == type
            || Integer.class == type) {
          metaCache.setValue(name, Integer.valueOf(value));
        } else if (long.class == type
            || Long.class == type) {
          metaCache.setValue(name, Long.valueOf(value));
        } else if (short.class == type
            || Short.class == type) {
          metaCache.setValue(name, Short.valueOf(value));
        } else if (byte.class == type
            || Byte.class == type) {
          metaCache.setValue(name, Byte.valueOf(value));
        } else if (float.class == type
            || Float.class == type) {
          metaCache.setValue(name, Float.valueOf(value));
        } else if (boolean.class == type
            || Boolean.class == type) {
          metaCache.setValue(name, Boolean.valueOf(value));
        } else if (double.class == type
            || Double.class == type) {
          metaCache.setValue(name, Double.valueOf(value));
        } else {
          throw new CacheException("Unsupported property type for cache: '" + name + "' of type " + type);
        }
      }
    }
  }
}
 
Example #21
Source File: MetricInterceptor.java    From mybatis-boost with MIT License 5 votes vote down vote up
@Override
public Object intercept(Invocation invocation) throws Throwable {
    BoundSql boundSql = ((StatementHandler) invocation.getTarget()).getBoundSql();

    String sql = boundSql.getSql().replaceAll("\\s*\\n\\s*", " ");
    List<Object> parameters = new ArrayList<>();
    if (configuration.isShowQueryWithParameters()) {
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        Object parameterObject = boundSql.getParameterObject();
        MetaObject metaObject = MyBatisUtils.getMetaObject(parameterObject);
        if (parameterMappings.size() == 1 && !(parameterObject instanceof Map) &&
                !metaObject.hasGetter(parameterMappings.get(0).getProperty())) {
            parameters.add(parameterObject);
        } else {
            parameterMappings.forEach(pm -> parameters.add(metaObject.getValue(pm.getProperty())));
        }
    }

    StopWatch stopWatch = StopWatch.createStarted();
    Object proceed = invocation.proceed();
    long time = stopWatch.getTime();
    if (time > configuration.getSlowQueryThresholdInMillis()) {
        if (parameters.isEmpty()) {
            logger.error(String.format("[SLOW Query took %s ms] %s", time, sql));
        } else {
            logger.error(String.format("[SLOW Query took %s ms, Parameters: %s] %s ", time, parameters, sql));
        }
        BiConsumer<String, Long> slowSqlHandler = configuration.getSlowQueryHandler();
        if (slowSqlHandler != null) {
            slowSqlHandler.accept(sql, time);
        }
    } else if (configuration.isShowQuery()) {
        if (parameters.isEmpty()) {
            logger.info(String.format("[Query took %s ms] %s", time, sql));
        } else {
            logger.info(String.format("[Query took %s ms, Parameters: %s] %s ", time, parameters, sql));
        }
    }
    return proceed;
}
 
Example #22
Source File: MyBatisUtils.java    From platform with Apache License 2.0 5 votes vote down vote up
/**
 * 获取真实代理对象
 *
 * @param target Object
 * @param <T>    T
 * @return T
 */
public static <T> T getRealTarget(Object target) {
    if (Proxy.isProxyClass(target.getClass())) {
        MetaObject metaObject = SystemMetaObject.forObject(target);
        return getRealTarget(metaObject.getValue("h.target"));
    }
    return (T) target;
}
 
Example #23
Source File: EntityMetaObjectHandler.java    From albedo with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void insertFill(MetaObject metaObject) {
	if (checkMetaObject(metaObject)) {
		setFieldValByName(BaseDataEntity.F_CREATEDBY, auditorAware.getCurrentAuditor().get(), metaObject);
		LocalDateTime date = LocalDateTime.now();
		setFieldValByName(BaseDataEntity.F_CREATEDDATE, date, metaObject);
		setFieldValByName(BaseDataEntity.F_LASTMODIFIEDBY, auditorAware.getCurrentAuditor().get(), metaObject);
		setFieldValByName(BaseDataEntity.F_LASTMODIFIEDDATE, date, metaObject);
	}

}
 
Example #24
Source File: Save.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) {
    super.replace(connection, metaObject, mappedStatement, boundSql);
    String sql = boundSql.getSql();
    Matcher matcher = PATTERN_COLUMNS.matcher(sql);
    if (matcher.find()) {
        StringBuilder builder = new StringBuilder(sql);
        builder.append(" ON DUPLICATE KEY UPDATE ");
        Arrays.stream(matcher.group(1).split(", "))
                .forEach(it -> builder.append(it).append(" = VALUES(").append(it).append("), "));
        builder.setLength(builder.length() - 2);
        metaObject.setValue("delegate.boundSql.sql", builder.toString());
    }
}
 
Example #25
Source File: DispatcherInterceptor.java    From mybatis-boost with MIT License 5 votes vote down vote up
@Override
public Object intercept(Invocation invocation) throws Throwable {
    Connection connection = (Connection) invocation.getArgs()[0];
    MetaObject metaObject = MyBatisUtils.getMetaObject(invocation.getTarget());
    MappedStatement mappedStatement = (MappedStatement) metaObject.getValue("delegate.mappedStatement");
    BoundSql boundSql = (BoundSql) metaObject.getValue("delegate.boundSql");
    preprocessors.forEach(p -> p.replace(connection, metaObject, mappedStatement, boundSql));
    providers.forEach(p -> p.replace(connection, metaObject, mappedStatement, boundSql));
    return invocation.proceed();
}
 
Example #26
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 #27
Source File: LimiterSqlProvider.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) {
    SqlProvider provider = this.provider;
    if (provider == null || configuration.isMultipleDatasource()) {
        try {
            String databaseName = connection.getMetaData().getDatabaseProductName();
            this.provider = provider = providerMap.get(databaseName);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    if (provider != null) {
        provider.replace(connection, metaObject, mappedStatement, boundSql);
    }
}
 
Example #28
Source File: GetByPrimaryKeyBuilder.java    From azeroth with Apache License 2.0 5 votes vote down vote up
/**
 * 设置返回值类型
 *
 * @param ms
 * @param entityClass
 */
private static void setResultType(Configuration configuration, MappedStatement ms, Class<?> entityClass) {
    List<ResultMap> resultMaps = new ArrayList<ResultMap>();
    resultMaps.add(getResultMap(configuration, entityClass));
    MetaObject metaObject = SystemMetaObject.forObject(ms);
    metaObject.setValue("resultMaps", Collections.unmodifiableList(resultMaps));
}
 
Example #29
Source File: MetaObjectAssistant.java    From Aooms with Apache License 2.0 5 votes vote down vote up
public 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 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());
 }