【Mybatis】【10】foreach 批量操作

正文:

1,foreach属性

属性 是否必选 描述
item 元素进行迭代时的别名
collection 要做迭代的数据集合
separator 元素之间的分隔符
open 表示该语句以什么开始
close 表示该语句以什么结束
index 每次迭代到的位置

2,select count(1) from user where id in ( ? , ? ) 

一定要注意到$和#的区别,$的参数直接输出,#的参数会被替换为?,然后传入参数值执行。

<select id="test" resultType="int">  
  select count(1) from user  
  <where>  
    id in  
    <foreach item="item" collection="list" separator="," open="(" close=")" index="">  
      #{item.id}  
    </foreach>  
  </where>  
</select> 

3,select count(1) from user  where col_a = ? and col_b = ?  

<select id="test" resultType="int">  
    select count(1) from user where  
    <foreach item="item" index="key" collection="map" open="" separator="AND" close="">
    ${key} = #{item}
    </foreach>  
</select>

 

4,Oracle :insert into user select ?,? from dual union all select ?,? from dual

<insert id="test">        
    insert into user (id, name)     
    <foreach collection="userList" item="item" separator="UNION ALL">
        select #{item.id}, #{item.name} from user_temp
    </foreach>
</insert>

5,Mysql :insert into user(key, value) values (?, ?) , (?, ?) 

<insert id="test">  
    insert into user(key, value) values  
    <foreach item="item" index="key" collection="map" open="" separator="," close="">
    (#{key}, #{item})
    </foreach>  
</insert> 

参考博客:

Mybatis foreach 批量操作 - jason5186 - CSDN博客
https://blog.csdn.net/jason5186/article/details/40896043

posted @ 2019-06-20 09:04  花生喂龙  阅读(402)  评论(0编辑  收藏  举报