mybatis 批量新增、修改

在公司项目开发中,遇到批量数据插入或者更新,因为每次连接数据库比较耗时,所以决定改为批量操作,提升效率。

经测试,一共1662条数据,批量插入用时466ms,循环单独插入用时1898ms。可以批量操作效率高很多。

1:数据库连接代码中必须开启批量操作。加上这句,&allowMultiQueries=true,完整的如下:

jdbc:mysql://localhost:3306/jeesite2016?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true

2、批量插入

<insert id="batchInsert" parameterType="java.util.List">  
        INSERT INTO erp_store_detail(  
            id,  
            store_id,  
            type,  
            change_quantity,  
            after_quantity,  
            update_date,  
            remarks,  
            link_id  
        ) VALUES   
     <foreach collection="list" item="item" index="index" separator="," >    
        (  
            #{item.id},  
            #{item.store.id},  
            #{item.type},  
            #{item.changeQuantity},  
            #{item.afterQuantity},  
            #{item.updateDate},  
            #{item.remarks},  
            #{item.linkId}  
        )  
     </foreach>        
    </insert>  

3:批量更新和批量插入是不一样的。

<update id="batchUpdateQuantity" parameterType="java.util.List">  
                  <foreach collection="list" item="item" index="index"  open="" close="" separator=";">  
                  update erp_store   
                  <set>   
                  quantity=#{item.quantity},  
                  update_date=#{item.updateDate}  
                  </set>   
                  where id = #{item.id}  
                 </foreach>  
    </update>  

DAO层代码:

void insertCount(List<VisitorCount> insertBatch);对于新增时的非空判断:

最多你需要为可能为空的列名指定 jdbcType。 #{middleInitial,jdbcType=VARCHAR}

猜你喜欢

转载自blog.csdn.net/a116385895/article/details/88641454