Skip to content

Commit 62fe78a

Browse files
committed
fixes #195 foreach element outputs open and close values even when the passed collection is empty.
1 parent 81fc432 commit 62fe78a

File tree

2 files changed

+17
-0
lines changed

2 files changed

+17
-0
lines changed

src/main/java/org/apache/ibatis/scripting/xmltags/ForEachSqlNode.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,9 @@ public ForEachSqlNode(Configuration configuration, SqlNode contents, String coll
5252
public boolean apply(DynamicContext context) {
5353
Map<String, Object> bindings = context.getBindings();
5454
final Iterable<?> iterable = evaluator.evaluateIterable(collectionExpression, bindings);
55+
if (!iterable.iterator().hasNext()) {
56+
return true;
57+
}
5558
boolean first = true;
5659
applyOpen(context);
5760
int i = 0;

src/test/java/org/apache/ibatis/builder/xml/dynamic/DynamicSqlSourceTest.java

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -317,6 +317,20 @@ public void shouldIterateOnceForEachItemInCollection() throws Exception {
317317
assertEquals("__frch_item_2", boundSql.getParameterMappings().get(2).getProperty());
318318
}
319319

320+
@Test
321+
public void shouldSkipForEachWhenCollectionIsEmpty() throws Exception {
322+
final HashMap<String, Integer[]> parameterObject = new HashMap<String, Integer[]>() {{
323+
put("array", new Integer[] {});
324+
}};
325+
final String expected = "SELECT * FROM BLOG";
326+
DynamicSqlSource source = createDynamicSqlSource(new TextSqlNode("SELECT * FROM BLOG"),
327+
new ForEachSqlNode(new Configuration(), mixedContents(
328+
new TextSqlNode("#{item}")), "array", null, "item", "WHERE id in (", ")", ","));
329+
BoundSql boundSql = source.getBoundSql(parameterObject);
330+
assertEquals(expected, boundSql.getSql());
331+
assertEquals(0, boundSql.getParameterMappings().size());
332+
}
333+
320334
@Test
321335
public void shouldPerformStrictMatchOnForEachVariableSubstitution() throws Exception {
322336
final Map<String, Object> param = new HashMap<String, Object>();

0 commit comments

Comments
 (0)