前言

  • springboot 2.1.1.RELEASE

分割字符串

<select id="selectXXXList" parameterType="XXX" resultMap="XXXResult">
	select * from xxx
    <where>  
        <if test="tagIds != null  and tagIds != ''"> and 
         	<foreach item="tagId" collection="tagIds.split(',')" open="(" separator=" or " close=")">
          		FIND_IN_SET (#{tagId}, tag_ids)
      		</foreach>
        </if>
    </where>
</select>
  • <if test="tagIds != null and tagIds != ''"> ... collection="tagIds.split(',')" ... </if>tagIds 是调用 selectXXXList 时传入的参数
  • ... <foreach item="tagId" collection="tagIds.split(',')" ...> ...: 对tagIds 调用 split 函数,将 tagIds 进行分割。foreach 遍历分割后的数据。每次遍历时,数据赋值给tagId变量。
  • ... <foreach item="tagId" ... separator=" or " ...> FIND_IN_SET (#{tagId}, tag_ids) </foreach> ...: 得到 FIND_IN_SET (#{tagId}, tag_ids) or FIND_IN_SET (#{tagId}, tag_ids) or ...

tagIds=1,2 时的执行效果:

SQL: select * from xxx where (FIND_IN_SET (#{tagId}, tag_ids) or FIND_IN_SET (#{tagId}, tag_ids))
参数: 1(String)2(String)

更多推荐

【Mybatis】分割字符串