Mybatis批量增加、批量更新、批量删除和查询

之前项目由于需要处理短时间内大量数据入库的问题。想到了Mybatis的批量操作。这里对这些操作进行一下记录,重点是批量增加和更新。

一、批量增加

    <!-- 批量增加操作 -->
    <insert id="batchInsertUsers" parameterType="java.util.List">
        insert into user(userName,password) values
        <foreach collection="list" item="item" index="index" separator=",">
            (#{item.userName},#{item.password})
        </foreach>
    </insert>

二、批量删除

<!-- 批量删除操作 -->
    <delete id="batchDeleteUsers" parameterType="java.util.List">
        delete from user where id in
        <foreach collection="list" index="index" item="item" open="(" close=")" separator=",">
            #{item.id}
        </foreach>
    </delete>

三、批量更新

批量更新网上查到的大部分是这种形式:

    <!-- 批量更新操作 -->
    <update id="batchUpdateUsers" parameterType="java.util.List">
        <foreach collection="list" item="item" index="index" open="" close="" separator=";">
        update user
        <set>
            userName = #{item.userName}, password = #{item.password}
        </set>
        where id = #{item.id}
        </foreach>
    </update>

这种更新方式说是批量更新。其实实质上是一条记录执行一次update的sql,对数据库而言,还是多条sql,性能不好,容易造成阻塞。Mysql没有提供直接的方法来实现批量更新,但是我们可以通过使用 case when来实现这一功能:

UPDATE course
    SET name = CASE id 
        WHEN 1 THEN 'name1'
        WHEN 2 THEN 'name2'
        WHEN 3 THEN 'name3'
    END, 
    title = CASE id 
        WHEN 1 THEN 'New Title 1'
        WHEN 2 THEN 'New Title 2'
        WHEN 3 THEN 'New Title 3'
    END
WHERE id IN (1,2,3)

代码示例如下:

<update id="updateBatch" parameterType="list">
            update user
            <trim prefix="set" suffixOverrides=",">
             <trim prefix="id=case" suffix="end,">
                 <foreach collection="list" item="i" index="index">
                         <if test="i.id!=null">
                          when id=#{i.id} then #{i.id}
                         </if>
                 </foreach>
              </trim>
              <trim prefix=" name=case" suffix="end,">
                 <foreach collection="list" item="i" index="index">
                         <if test="i.name!=null">
                          when id=#{i.id} then #{i.name}
                         </if>
                 </foreach>
              </trim>
             </trim>
            where
            <foreach collection="list" separator="or" item="i" index="index" >
              id=#{i.id}
          </foreach>
</update>

四、批量查询

    <!-- 批量查询操作 -->
    <select id="batchSelectUsers" resultType="User">
        select *
        from user where id in
        <foreach collection="list" index="index" item="item" open="(" separator="," close=")">
        #{item.id}
        </foreach>
    </select>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值