mybatis传入逗号串查询

myBatis通过逗号分隔字符串,foreach 前言 当数据库里存储的值是以逗号分隔格式存储的字符串时。 数据格式如下:

id name ids 1 张三 a,b,c 2 李四 c,d,e

我们拿到的条件参数是:b,e 1.后台通过逗号分隔数组,生成查询语句 select * from table where ids in (’b’,’e’)

2.通过myBatis自带功能foreach,直接把逗号分隔的字符串传到mapper.xml即可,后台不用过多操作。
<select id="getSimilarity" parameterType="java.util.HashMap" resultType="java.util.HashMap">
    select * from table
    where ids in 
    <foreach item="item" index="index" collection="ids.split(,)"  open="(" separator="," close=")">
                #{item}
    </foreach>
  </select>

注:ids就是传入的参数名称,如果报错请检查参数名称是否正确,参数是否有值。 后台代码(我这里有需要其他参数,所以用的map举例): Map<String, Object> map = new HashMap<String, Object>(); map.put(“ids”, “b,e”); List<Map<String, Object>> list = tableService.getSimilarity(map);

控制台打印SQL:

Preparing: select * from table where ids in ( ? , ? ) Parameters: b(String), e(String)

经验分享 程序员 微信小程序 职场和发展