使用Mybatis做批量插入

最近有个需求,将excel的数据导入的数据库的这个一个操作。 
工作主要分为:解析excel,将excel中的数据单条循环插入数据库。 
使用框架:mybatis+spring 
使用过Mybatis的人都知道,自动生成的Mapper里是不支持批量插入的,也不支持SQL。这个让我有点小小的郁闷,网上查资料发现对这方面的资料颇少。于是决定写一篇blog案例分享心得。 
或许有人要问既然Mybatis既然支持插入了,为何非要要使用批量插入。我这里的excel中的数据最少也是上W条,如果是使用单条循环插入的话会对数据库造成很大的负荷状态,数据库的连接资源是有限的,循环插入的时候会直接的影响其它的数据库操作。 

 

package me.gall.business.model.mybatis.bean;  
  
/** 
 * @author Quinn He 
 * @dateTime 2012-2-9 下午4:35:18 
 * 
 */  
public class ApkStatisticRaw {  
  
    private Integer id;  
    private String uuid;  
    private String apkId;  
    private String eventId;  
    private Integer supplyId;  
    private Integer channelId;  
    private String fileUploadRecordId;  
    private String productName;  
    private String content;  
    private Long time;  
    private Integer numbers;  
    private Integer status;  
    private String creator;  
    private Long createTime;  
    private String other;  
  
    set...  
         get...  
  
  
}  

interface

 

import me.gall.business.model.mybatis.bean.ApkStatisticRaw;  
  
/** 
 * @author Quinn He 
 * @dateTime 2012-2-20 下午7:48:39 
 */  
public interface ApkStatisticRawExtMapper {  
  
/** 
     * 专门针对在导入CSV文件时 
     * 频繁操作数据库造成的数据库并发问题 
     * 固此方法为批量插入方法 
     *  
     * @author Quinn He 
     * @dateTime 2012-3-30 上午11:34:22 
     * @param list 
     */  
    void batchInsert(List<ApkStatisticRaw> list);  
}  

再看看XML里的操作 

<select id="batchInsert" parameterType="java.util.List">  
        insert into apk_statistic_raw  
        (uuid,apk_id,event_id,supply_id,channel_id,file_upload_record_id,product_name,content,time,numbers,status,creator,create_time,other  
        )values  
        <foreach collection="list" item="item" index="index"  
            separator=",">  
            (#{item.uuid,jdbcType=CHAR},#{item.apkId,jdbcType=CHAR},#{item.eventId,jdbcType=CHAR},#{item.supplyId,jdbcType=INTEGER},#{item.channelId,jdbcType=INTEGER}  
            ,#{item.fileUploadRecordId,jdbcType=CHAR},#{item.productName,jdbcType=VARCHAR},#{item.content,jdbcType=VARCHAR},#{item.time,jdbcType=BIGINT},  
            #{item.numbers,jdbcType=INTEGER},#{item.status,jdbcType=INTEGER},#{item.creator,jdbcType=VARCHAR},#{item.createTime,jdbcType=BIGINT},#{item.other,jdbcType=VARCHAR}  
            )  
        </foreach>  
    </select> 

如此简单的操作,我也不做多说吧。相信都能看懂#{item.uuid,jdbcType=CHAR}其中uuid是对象的字段,CHAR是对应的数据库字段类型 

 

 

转载于:https://www.cnblogs.com/google4y/p/3309364.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值