Mybatis查询中使用foreach的三种用法

文章作者:杨仙僧
文章地址:https://blog.csdn.net/lin252552/article/details/82691994

foreach一共有List,array,Map三种类型的使用场景。foreach的主要用在构建in条件中,它可以在SQL语句中进行迭代一个集合。

  • item表示集合中每一个元素进行迭代时的别名,
  • index指定一个名字,用于表示在迭代过程中,每次迭代到的位置,
  • open表示该语句以什么开始,
  • separator表示在每次进行迭代之间以什么符号作为分隔 符,
  • close表示以什么结束。
1、List类型插入:(处理层传入 - 集合)
<insert id="batchInsertClientDeviceList" parameterType="java.util.List" >
    INSERT INTO t_client_device_list (order_no,mac_id,client_code,status,order_time)
    <foreach collection="list" item="item" index="index" separator="union all">
         select #{item.orderNo, jdbcType=VARCHAR},#{item.macId, jdbcType=VARCHAR}
         from dual
    </foreach>
</insert>

2、Array类型查询:(处理层传入 - 数组)
<select id="getClientDeviceList" parameterType="java.util.ArrayList" resultType="Device">
     select * from t_devices where id in
     <foreach collection="array" index="index" item="item" open="(" separator="," close=")">
          #{item}
     </foreach>
</select>   

3、参数Map类型查询:(处理层传入 - params.put(“ids”,集合或数组))

map中存放了一个元素key为ids,value为List用于id in的条件

<select id="getClientDeviceList" parameterType="java.util.HashMap" resultType="Device">
    select * from t_devices where mac like "%"#{mac}"%" and id in
    <foreach collection="ids" index="index" item="item" open="(" separator="," close=")">
        #{item}
    </foreach>
</select>

当参数为map时,foreach中的conection必须为参数名,不能写成list 或者 array ,否者报错:The expression ‘list’ evaluated to a null value详情请见此篇文章: https://blog.csdn.net/qq_36698956/article/details/90204225

4、参数Map类型查询:(处理层传入 - params.put(“ids”,“a,b,c”))

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

select * from table where ids in (’b’,’e’)
  1. 通过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>

作为查询条件查询时加if判断参数是否为空

<select id="getSimilarity" parameterType="java.util.HashMap" resultType="java.util.HashMap">
    select * from table
    where 1=1
    <if test="ids !=null and ids !=''">
    and	ids in 
    <foreach item="item" index="index" collection="ids.split(’,’)"  open="(" separator="," close=")">
                #{item}
    </foreach>
    </if>
  </select>

注:ids就是传入的参数名称,如果报错请检查参数名称是否正确,参数是否有值。
3. 后台代码(我这里有需要其他参数,所以用的map举例):

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

4.控制台打印SQL:

Preparing: select * from table where ids in ( ? , ?  ) 
Parameters: b(String), e(String)
  • 1
    点赞
  • 32
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值