myBatis的增,删,改,批量操作sql

针对如下一个学生信息表进行操作
在这里插入图片描述

1:foreach遍历增加数据

<insert id="addBatchData">
        insert into student(name,email,age,address,sex) values
        <foreach collection="list" open="" close="" separator="," item="sm">
            (#{sm.name},#{sm.email},#{sm.age},#{sm.address},#{sm.sex})
        </foreach>
    </insert>

日志输出:insert into student(name,email,age,address,sex) values (?,?,?,?,?) , (?,?,?,?,?) , (?,?,?,?,?)

2:批量删除数据

传入参数:删除id所拼接的字符串

<delete id="deleteBatchData">
        delete from student where id in
        <foreach collection="ids.split(',')" open="(" close=")" separator="," item="item">
            #{item}
        </foreach>
    </delete>

日志输出:delete from student where id in ( ? , ? )

3:批量修改数据

<update id="updateBatchData">
        update student
        set  name=
        <foreach collection="list" item="item" index="index"
                 separator=" " open="case ID" close="end">
            when #{item.id} then #{item.name}
        </foreach>,
        email=
        <foreach collection="list" item="item" index="index"
                 separator=" " open="case ID" close="end">
            when #{item.id} then #{item.email}
        </foreach>
        where id in
        <foreach collection="list" index="index" item="item"
                 separator="," open="(" close=")">
            #{item.id}
        </foreach>
    </update>

日志输出:update student set name= case ID when ? then ? when ? then ? end , email= case ID when ? then ? when ? then ? end where id in ( ? , ? )

发布了27 篇原创文章 · 获赞 1 · 访问量 859

猜你喜欢

转载自blog.csdn.net/weixin_44971379/article/details/104603007