Mybatis 批量插入

来源:互联网 发布:淘宝有货到付款吗 编辑:程序博客网 时间:2024/06/07 03:30

阿里云股票业务有提供一项查询功能,发送股票名称,返回股票编码,在毕业设计的开发过程中,我用到了这个功能。由于需要支付费用,毕设结束后便考虑自己动手实现。

找到了这个地址:http://quote.eastmoney.com/stock_list.html

对股票信息数据进行抓取后入库,有4000多条数据,如果采用传统的入库方式,一条条数据插入,数据库I/O会浪费比较大的资源。


尝试了后,数据如下:本次新增股票数据共4337条,耗时233秒

后面决定使用Mybatis的批处理操作,采用的方式,主要是在mapper文件中使用了foreach标签,举个简单的例子,插入一条语句,是

insert into xxx values xx、xx、xx

现在变成了

insert into xxx values (xx、xx、xx,xx、xx、xx....)

将下一条记录的值直接拼接在sql后面。

批量插入的数据是:本次新增股票数据共4337条,耗时11秒,相比于传统的插入方式,快了20倍,当然,这是比较模糊的数据,在后台的实现中,我是设置为数据量达到1000,就进行插入操作。


具体实现如下:

后台代码


int newCount = 0;        long startTime = System.currentTimeMillis();        List<SharesInfo> list = new ArrayList<SharesInfo>();        for (Element ele:eles) {            String text = ele.text();            String name = TextUtil.RegexMatch("(.*)\\(",text,1);            String code = TextUtil.RegexMatch("\\((.*)\\)",text,1);            try{                SharesInfo temp = sharesInfoService.selectBySharesName(name);                if(temp == null) {                    SharesInfo sharesInfo = new SharesInfo();                    sharesInfo.setCode(code);                    sharesInfo.setName(name);                    //sharesInfoService.addSharesInfo(sharesInfo);                    list.add(sharesInfo);                    if(list.size() == 1000){                        sharesInfoService.addSharesInfoBatch(list);                        list.clear();                    }                    newCount ++ ;                }            }catch (Exception e){                logger.error(name);            }        }        //把零头也进行入库        sharesInfoService.addSharesInfoBatch(list);        long endTime = System.currentTimeMillis();        logger.info("本次新增股票数据共"+newCount+"条,耗时"+(endTime-startTime)/1000+"秒");


Mapper.xml文件:

<insert id="insertBatch" parameterType="java.util.List" >    insert into sharesinfo (id, code, name    )    values    <foreach collection ="list" item="info" index= "index" separator =",">    (#{info.id,jdbcType=INTEGER}, #{info.code,jdbcType=VARCHAR}, #{info.name,jdbcType=VARCHAR})    </foreach>  </insert>


Service层

public void addSharesInfoBatch(List<SharesInfo> list);


还算是比较简单,这种实现方式可应用于常用的批处理插入方式,但如果是存在大数据类型的,就不可用这种方式了

原创粉丝点击