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

前言java

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

数据格式以下:数组

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

咱们拿到的条件参数是:b,eapp

    1.后台经过逗号分隔数组,生成查询语句spa

select * from table where ids in (’b’,’e’)

 

    2.经过myBatis自带功能foreach,直接把逗号分隔的字符串传到mapper.xml便可,后台不用过多操做。code

<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就是传入的参数名称,若是报错请检查参数名称是否正确,参数是否有值。xml

    后台代码(我这里有须要其余参数,因此用的map举例):blog

Map<String, Object> map = new HashMap<String, Object>(); map.put("ids", "b,e"); List<Map<String, Object>> list = tableService.getSimilarity(map);

 

    控制台打印SQL:ci

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

 

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

原文章地址:https://www.wanpishe.top/detail?blogId=555f6b2a-cd80-4c55-8174-c96ac898ec9f

相关文章
相关标签/搜索