Mybatis的foreach可以很好遍历集合,那么使用这个元素需要注意的是当遍历的是list的时候呢,collection的值应为list,当遍历其他如set,则collection的值应为collection。原因如下是核心源码
private Object wrapCollection(Object object) {
DefaultSqlSession.StrictMap map;
if (object instanceof Collection) {
map = new DefaultSqlSession.StrictMap();
map.put("collection", object);
if (object instanceof List) {
map.put("list", object);
}
return map;
} else if (object != null && object.getClass().isArray()) {
map = new DefaultSqlSession.StrictMap();
map.put("array", object);
return map;
} else {
return object;
}
}