mybatis中foreach标签的使用

<insert id="insertBatch">
    inset into users(username,brithday,sex,address) values
        <foreach collection="list" item="user" separator=",">
            
        </foreach>
</insert>

foreah标签主要是用来进行集合或数组的遍历主要有以下的参数:

        collection:属性的值为 list array map  就是参数位置传过来的类型三种分别对应的参数是List 数组 map集合

 应用场景:查询多个指定id的用户信息

接口:

List<User>getByIds(Integer arr[]);

在编写mapper文件的时候当入参是数组集合map,参数超过一个时候参数parameterType省略

mapper.xml:  就是吧数组中传过来的参数进行一个遍历 加入数组的内容是1,2,3那么查询的内容就是id 是1,2,3的数据

item是每次遍历出来的对象或者值 名字可以任意

 separator是多个值或对象之间的分隔符

open是整循环的前括号

close是整个循环的后括号

<select id="getByIds" resultType="users">
    select * from users where id in(
                <foreach collection="array" item="item" separator="," open="(" close=")">
                        #{id}
                </foreach>    
            
            )
</select>

案例:批量删除

int deleteBatch(Integer arr[]);

mapper.xml

<delete id="deleteBarch">
    delete from users where id in 
        <foreach  collecton="array" separator="," open="(" close=")" item="id">
            @{id}
        </foreach>
</delete>

批量增加 注意这个不需要加前后括号因为插入值每插入一个值都是一个括号括号是在里面的同时使用逗号进行分隔只要了解sql语句理解

int  insertBatch(List<Users> list);

mapper.xml

<insert id="insertBatch">
    insert into users values
            <foreach collection="list" item="user" separator=",">
               (#{user.username},#{user.password},#{user.sex},#{user.address})     
            </foreach>
</insert>

批量更新

注意:如果想要使用批量更新必须在链接数据库的配置文件中url中添加&allowMultiQueries=true允许多行操作才可以执行

<!--  separator=";"用分号隔开是因为每一条更新语句都是独立的  -->
    <update id="updateSet">
        <foreach collection="list" item="user" separator=";">
            update users
                <set>
                    <if test="user.username!=null and user.username!=''">
                        username=#{user.username}
                    </if>
                    <if test="user.password!=null and user.password!=''">
                        password=#{user.password}
                    </if>
                </set>
                where  id=#{user.id}
        </foreach>
    </update>

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值