1.问题说明
传递参数如下:
Map<String, Object> parameter = new HashMap<>(2); parameter.put("test","少儿','历史"); commonMapper.test(parameter);
Mapper内的SQL如下:
<select id="test" parameterType="map" resultType="map"> SELECT * FROM test WHERE NAME IN ( #{test} ) </select>
实际执行的SQL如下:
Execute SQL:SELECT * FROM test WHERE NAME IN ( '少儿'',''历史' )
想要执行的SQL:
SELECT * FROM test WHERE NAME IN ( '少儿','历史' )
2.问题解决
2.1 方案一
Java代码拼写inStr
:
/** * 带逗号的字符串转换成SQL里的inStr("a,b,c"->'a','b','c') * * @param stringWithComma 用逗号分隔的字符串 "a,b,c" * @return inStr可以用在SQL的in语句内 'a','b','c' */ public String getInStr(String stringWithComma) { String splitSymbolComma = ","; ArrayList<String> strList = CollectionUtil.toList(stringWithComma.split(splitSymbolComma)); return strList.stream().collect(Collectors.joining("\',\'", "\'", "\'")); }
此时Mapper使用${}
进行注入:
<select id="test" parameterType="map" resultType="map"> SELECT * FROM test WHERE NAME IN ( ${test} ) </select>
2.2 方案二
将in参数转换成array
或list
传递给Mapper动态生成筛选SQL:
<delete id="test" parameterType="map"> SELECT * FROM test WHERE NAME IN <foreach collection="array" item="type" open="(" separator="," close=")"> #{type} </foreach> </delete> <delete id="test" parameterType="map"> SELECT * FROM test WHERE NAME IN <foreach collection="list" item="type" open="(" separator="," close=")"> #{type} </foreach> </delete>