Mybatis批量插入

mappers文件中的#{}语法与${}语法的区别:

    默认情况下, #{}语法会促使MyBatis生成PreparedStatement属性并且使用PreparedStatement的参数(=?)来设置值。如果你想直接将未更改的字符串代入到sql中,可以使用${}。

 

mybatis批量插入:

    使用INSERTINTO [TABLE]([FIELD],[FIELD]...)VALUES([VALUE],[VALUE]...),([VALUE],[VALUE]...)...  比使用insert into XXX values(XX),insert into XXX values(XXX),insert into XXX values(XXX)效率要高。

但是,在一条命令SQL引擎默认是一次最多插入1000笔记录,最多2100个字段参数。所以插入的时候还要处理一下:

public int insertPartList(List<Part> parts){
     int rs=0;
     int dealNum = 520;// 每次批处理条数
     for(int i=0,s=0;i<parts.size()/dealNum;i++,s+=dealNum)
         rs+=getSqlSession().insert("insertPartList",parts.subList(s,s+dealNum));
     
     // 处理剩余部分
     int afterNum = (parts.size()/dealNum)*dealNum;
     if(parts.size()-afterNum >0)
         rs+=getSqlSession().insert("insertPartList",parts.subList(afterNum,parts.size()));
     return rs;
}

 

<insert id="insertBatch" useGeneratedKeys="true" parameterType="java.util.List">  
   <selectKey resultType="long" keyProperty="id" order="AFTER">  
       SELECT  
       LAST_INSERT_ID()  
   </selectKey>  
   insert into table1 (<include refid="Base_Column_List" />)   
   values  
   <foreach collection="list" item="item" index="index" separator="," >  
       (#{item.name},#{item.sex},#{item.address},#{item.telephone})  
   </foreach>  
</insert>

 

可以用union all来实现批量插入。
例如:
insert into TABLE(XX,XX,XX)select 'xx','xx','xx' union all select 'xx','xx','xx' union all select 'xx','xx','xx' ...
先拼装好语句再动态传入insert into TABLE(XX,XX,XX)后面部分

<insert id="insertBatch2" useGeneratedKeys="true" parameterType="java.util.List">    
  INSERT INTO table1 (<include refid="Base_Column_List" />)     
  VALUES
  <foreach collection="list" item="item" index="index" separator="union all">
      select #{item.name,jdbcType=VARCHAR},#{item.sex,jdbcType=VARCHAR},#{item.address,jdbcType=VARCHAR},#{item.telephone,jdbcType=VARCHAR} from dual 
  </foreach>    
</insert>

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值