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

来源:互联网 发布:最好听的网络歌曲 编辑:程序博客网 时间:2024/06/05 08:02

之前项目由于需要处理短时间内大量数据入库的问题。想到了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'    ENDWHERE 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>
原创粉丝点击