myBatis通过逗号分隔字符串,foreach

前言

    当数据库里存储的值是以逗号分隔格式存储的字符串时。

数据格式如下:

 idname ids 
 1  张三  b
 2  李四  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)

 

我这里就是简单举例,其他使用方式请各位大佬自行研究。

posted @ 2018-12-14 16:04  粉红顽皮蛇  阅读(28384)  评论(1编辑  收藏  举报