How mybatis accepts set collection parameters

Reason: In actual development, we use list for range query. Generally, it is known that the data in the list set is non-repeated data. If the repetition probability of the data in the set is high, the set set is used to remove the repeated parameters, and then the range query is performed.

Now the problem is, when calling the following method, when the parameter is directly passed the set collection, as follows:

Set<Integer> set = new HashSet<>();
set.add(2),
set.add(3),
return this.getCurSqlSessionTemplate().selectOne(Children.class.getName() + ".findChildren", set);

At this point, you add a foreach loop in the xml:

<foreach collection="set" open="(" separator="," close=")" item="val">
    ${val}
</foreach>

When running, it will throw that the set parameter cannot be found. If the parameter you pass is a Bean, the following param can solve the above problem, but the cause of the problem has not been found.

Map<String,Object> param = new HashMap<>();
param.put("set",set);

Next, find the cause of the problem. By tracking the source code, we will suddenly realize that the core content has been marked in red, mybatis itself encapsulates the parameter return value, the passed collection is a list and it is named list, and the others are all collections.

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;
        }
    }
Modify the foreach code in xml as follows, you can query it normally
<foreach collection="collection" open="(" separator="," close=")" item="val">
    ${val}
</foreach>
Summary: It is very important to program and track the source code. It can help you know why, not only know how to use it, because the rules are always changing, and the way to obtain the rules is the most critical.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325608744&siteId=291194637