Mybatis使用foreach参数失效,在不修改任何分页拦截器的情况下的解决办法
起因是这样,存的库表中有数组形式的json,然后需要对json字段进行查询,例如数据库中有三条记录分别包含这三个json数据:[1,2,3]; [2,3,4];[3,4] 此时需要查询包含2或4的记录,那么自然是这三条都要查询出来。
去网上查了一下mysq支持json的查询,所以sql大致是这样的
select * form notice(表名)
where xxx....
and (JSON_CONTAINS(notice.id_list, "3")
or JSON_CONTAINS(t_notice.id_list, "4"))
ORDER BY create_time desc
ps: JSON_CONTAINS(表名.json字段名称, "需要查询的条件"),而且双引号是必须的格式不能少,否则报错
刚开始我是想在mapper文件中用foreach把where条件循环拼出来就像这样。
select * form notice(表名)
<where>
<if test="noticeSearch.buildingIds != null and noticeSearch.buildingIds .size()>0">
(<foreach collection="noticeSearch.buildingIds " item="id" separator="or">
JSON_CONTAINS(t_notice.building_id_list, #{id})
</foreach>)
</if>
</where>
然鹅,,,天不遂人愿还是我太天真了(捂脸哭).数据是查出来了,但是谁承想分页竟然出了问题WTF??!
解决这个问题的时间是在两个月后的现在。。。身为社会主义接班人的我实在是不信这个邪,别人的分页就很完美,凭什么到我这儿就不行,然后就debug了一下结合网上的前辈们的博客,发现是项目中使用的分页拦截器进行总条数查询参数传递的时候把foreach的参数弄丢了,所以一直报错。org.apache.ibatis.binding.BindingException: Parameter ‘__frch_id_0’ not found. Available parameters are [noticeSearch, page, param1, param2]
问题是找着了,但是怎么改阿,以我目前的水平感jio够呛。。一个整不好分页给整叉劈了可是要罚钱的5555
正当我不知如何是好的时候,认识的小哥哥给我提供了另一种思路,干嘛要改拦截器,既然他会把foreach的参数弄丢,那在mapper中就不写foreach了,程序中直接将参数拼成串儿传进去不就完了么,这就很nice了,嘿嘿嘿。
所以就有了以下的改动,将之前写在mapper的循环写在了程序中
<!--改之前mapper>
select * form notice
<where>
xxx...
<if test="noticeSearch.buildingIds != null and noticeSearch.buildingIds .size()>0">
and ( <foreach collection="noticeSearch.buildingIds " item="id" separator="or">
JSON_CONTAINS(t_notice.building_id_list, #{id})
</foreach>)
</if>
</where>
// 用来替换foreach替换的代码
StringBuilder start = new StringBuilder("(");
List<String> ids = noticeSearch.getBuildingIdMapper();
// 拼接foreach , 并在中间都拼接 or
String sql = ids.stream().map(id -> new StringBuffer("JSON_CONTAINS(notice.d_list, \"")
.append(id).append("\")").toString()).collect(Collectors.joining(" or "));
StringBuilder end = new StringBuilder(")");
StringBuilder idstring = start.append(sql).append(end);
noticeSearch.setIdstring(new String(idstring));
ps:拼接完了之后在mapper中不能使用 #{}这样的占位符,需要换成 ${}
<!--改之后的mapper>
select * form notice
<where>
xxxx....
<if test="noticeSearch.idstring != null">
and ${noticeSearch.idstring}
</if>
</where>