org.apache.ibatis.scripting.xmltags.ForEachSqlNode Java Examples

The following examples show how to use org.apache.ibatis.scripting.xmltags.ForEachSqlNode. 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: ListParameterEnhancement.java    From mybatis-boost with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
private boolean filter(List<SqlNode> contents) {
    for (SqlNode content : contents) {
        if (content instanceof ForEachSqlNode) return false;
        for (Field field : content.getClass().getDeclaredFields()) {
            field.setAccessible(true);
            try {
                if (SqlNode.class.isAssignableFrom(field.getType())) {
                    if (!filter(Collections.singletonList((SqlNode) field.get(content)))) return false;
                } else if (Objects.equals(field.getGenericType().getTypeName(),
                        "java.util.List<org.apache.ibatis.scripting.xmltags.SqlNode>")) {
                    if (!filter((List<SqlNode>) field.get(content))) return false;
                }
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }
    }
    return true;
}
 
Example #2
Source File: DynamicSqlSourceTest.java    From mybaties with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldIterateOnceForEachItemInCollection() throws Exception {
  final HashMap<String, String[]> parameterObject = new HashMap<String, String[]>() {{
    put("array", new String[]{"one", "two", "three"});
  }};
  final String expected = "SELECT * FROM BLOG WHERE ID in (  one = ? AND two = ? AND three = ? )";
  DynamicSqlSource source = createDynamicSqlSource(
      new TextSqlNode("SELECT * FROM BLOG WHERE ID in"),
      new ForEachSqlNode(new Configuration(),mixedContents(new TextSqlNode("${item} = #{item}")), "array", "index", "item", "(", ")", "AND"));
  BoundSql boundSql = source.getBoundSql(parameterObject);
  assertEquals(expected, boundSql.getSql());
  assertEquals(3, boundSql.getParameterMappings().size());
  assertEquals("__frch_item_0", boundSql.getParameterMappings().get(0).getProperty());
  assertEquals("__frch_item_1", boundSql.getParameterMappings().get(1).getProperty());
  assertEquals("__frch_item_2", boundSql.getParameterMappings().get(2).getProperty());
}
 
Example #3
Source File: DynamicSqlSourceTest.java    From mybaties with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldPerformStrictMatchOnForEachVariableSubstitution() throws Exception {
  final Map<String, Object> param = new HashMap<String, Object>();
  final Map<String, String> uuu = new HashMap<String, String>();
  uuu.put("u", "xyz");
  List<Bean> uuuu = new ArrayList<Bean>();
  uuuu.add(new Bean("bean id"));
  param.put("uuu", uuu);
  param.put("uuuu", uuuu);
  DynamicSqlSource source = createDynamicSqlSource(
      new TextSqlNode("INSERT INTO BLOG (ID, NAME, NOTE, COMMENT) VALUES"),
      new ForEachSqlNode(new Configuration(),mixedContents(
          new TextSqlNode("#{uuu.u}, #{u.id}, #{ u,typeHandler=org.apache.ibatis.type.StringTypeHandler},"
              + " #{u:VARCHAR,typeHandler=org.apache.ibatis.type.StringTypeHandler}")), "uuuu", "uu", "u", "(", ")", ","));
  BoundSql boundSql = source.getBoundSql(param);
  assertEquals(4, boundSql.getParameterMappings().size());
  assertEquals("uuu.u", boundSql.getParameterMappings().get(0).getProperty());
  assertEquals("__frch_u_0.id", boundSql.getParameterMappings().get(1).getProperty());
  assertEquals("__frch_u_0", boundSql.getParameterMappings().get(2).getProperty());
  assertEquals("__frch_u_0", boundSql.getParameterMappings().get(3).getProperty());
}
 
Example #4
Source File: DynamicSqlSourceTest.java    From mybatis with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldIterateOnceForEachItemInCollection() throws Exception {
  final HashMap<String, String[]> parameterObject = new HashMap<String, String[]>() {{
    put("array", new String[]{"one", "two", "three"});
  }};
  final String expected = "SELECT * FROM BLOG WHERE ID in (  one = ? AND two = ? AND three = ? )";
  DynamicSqlSource source = createDynamicSqlSource(
      new TextSqlNode("SELECT * FROM BLOG WHERE ID in"),
      new ForEachSqlNode(new Configuration(),mixedContents(new TextSqlNode("${item} = #{item}")), "array", "index", "item", "(", ")", "AND"));
  BoundSql boundSql = source.getBoundSql(parameterObject);
  assertEquals(expected, boundSql.getSql());
  assertEquals(3, boundSql.getParameterMappings().size());
  assertEquals("__frch_item_0", boundSql.getParameterMappings().get(0).getProperty());
  assertEquals("__frch_item_1", boundSql.getParameterMappings().get(1).getProperty());
  assertEquals("__frch_item_2", boundSql.getParameterMappings().get(2).getProperty());
}
 
Example #5
Source File: DynamicSqlSourceTest.java    From mybatis with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldPerformStrictMatchOnForEachVariableSubstitution() throws Exception {
  final Map<String, Object> param = new HashMap<String, Object>();
  final Map<String, String> uuu = new HashMap<String, String>();
  uuu.put("u", "xyz");
  List<Bean> uuuu = new ArrayList<Bean>();
  uuuu.add(new Bean("bean id"));
  param.put("uuu", uuu);
  param.put("uuuu", uuuu);
  DynamicSqlSource source = createDynamicSqlSource(
      new TextSqlNode("INSERT INTO BLOG (ID, NAME, NOTE, COMMENT) VALUES"),
      new ForEachSqlNode(new Configuration(),mixedContents(
          new TextSqlNode("#{uuu.u}, #{u.id}, #{ u,typeHandler=org.apache.ibatis.type.StringTypeHandler},"
              + " #{u:VARCHAR,typeHandler=org.apache.ibatis.type.StringTypeHandler}")), "uuuu", "uu", "u", "(", ")", ","));
  BoundSql boundSql = source.getBoundSql(param);
  assertEquals(4, boundSql.getParameterMappings().size());
  assertEquals("uuu.u", boundSql.getParameterMappings().get(0).getProperty());
  assertEquals("__frch_u_0.id", boundSql.getParameterMappings().get(1).getProperty());
  assertEquals("__frch_u_0", boundSql.getParameterMappings().get(2).getProperty());
  assertEquals("__frch_u_0", boundSql.getParameterMappings().get(3).getProperty());
}
 
Example #6
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 #7
Source File: DynamicSqlSourceTest.java    From mybaties with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldSkipForEachWhenCollectionIsEmpty() throws Exception {
  final HashMap<String, Integer[]> parameterObject = new HashMap<String, Integer[]>() {{
      put("array", new Integer[] {});
  }};
  final String expected = "SELECT * FROM BLOG";
  DynamicSqlSource source = createDynamicSqlSource(new TextSqlNode("SELECT * FROM BLOG"),
      new ForEachSqlNode(new Configuration(), mixedContents(
          new TextSqlNode("#{item}")), "array", null, "item", "WHERE id in (", ")", ","));
  BoundSql boundSql = source.getBoundSql(parameterObject);
  assertEquals(expected, boundSql.getSql());
  assertEquals(0, boundSql.getParameterMappings().size());
}
 
Example #8
Source File: DynamicSqlSourceTest.java    From mybatis with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldSkipForEachWhenCollectionIsEmpty() throws Exception {
  final HashMap<String, Integer[]> parameterObject = new HashMap<String, Integer[]>() {{
      put("array", new Integer[] {});
  }};
  final String expected = "SELECT * FROM BLOG";
  DynamicSqlSource source = createDynamicSqlSource(new TextSqlNode("SELECT * FROM BLOG"),
      new ForEachSqlNode(new Configuration(), mixedContents(
          new TextSqlNode("#{item}")), "array", null, "item", "WHERE id in (", ")", ","));
  BoundSql boundSql = source.getBoundSql(parameterObject);
  assertEquals(expected, boundSql.getSql());
  assertEquals(0, boundSql.getParameterMappings().size());
}
 
Example #9
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 #10
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());
			}
		}
	}
}