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>

你可能感兴趣的:(mysql)