oracle merge into 批量新增或更新

mapper.java

    /**
     * 批量插入或更新
     * @param stpos
     * @author fengjia
     * @date 2022/5/9 19:50
     */
    void mergeInto(List<TbMmOtStpo> stpos);

mapper.xml

        merge into table_name u
        using
        (
        <foreach collection="list" index="index" item="item" open=""
                 close="" separator="union">
            SELECT #{item.stlty} as stlty,#{item.stlnr} as stlnr,#{item.stlkn} as stlkn,#{item.stpoz} as stpoz,#{item.datuv} as datuv,#{item.andat} as andat,#{item.aedat} as aedat,#{item.idnrk} as idnrk,#{item.pswrk} as pswrk,#{item.postp} as postp,#{item.posnr} as posnr,#{item.maktx} as maktx,#{item.vornr} as vornr,#{item.stvkn} as stvkn,#{item.plnnr} as plnnr,#{item.plnkn} as plnkn
            FROM dual
        foreach>
        ) t
        on (u.stlty = t.stlty and u.stlnr = t.stlnr and u.stlkn = t.stlkn and u.stpoz = t.stpoz)
        when matched then
        update set u.datuv = t.datuv,u.andat = t.andat,u.aedat = t.aedat,u.idnrk = t.idnrk,u.pswrk = t.pswrk,u.postp = t.postp,u.posnr = t.posnr,u.maktx = t.maktx,u.vornr = t.vornr,u.stvkn = t.stvkn,u.plnnr = t.plnnr,u.plnkn = t.plnkn,u.updatedtime = sysdate
        when not matched then
        insert (stlty,stlnr,stlkn,stpoz,datuv,andat,aedat,idnrk,pswrk,postp,posnr,maktx,vornr,stvkn,plnnr,plnkn,createdtime) VALUES(t.stlty,t.stlnr,t.stlkn,t.stpoz,t.datuv,t.andat,t.aedat,t.idnrk,t.pswrk,t.postp,t.posnr,t.maktx,t.vornr,t.stvkn,t.plnnr,t.plnkn,sysdate)
  1. merge into 后面跟表名
  2. using 更新数据,可以用union all 或者union 批量拼接数据
  3. on 判断更新还是插入的条件
  4. update 更新语句
  5. insert 插入语句
  • 问题1:更新的数据要通过on后面的条件找到唯一一条需要更新的数据,如果on后面的条件找到多条数据,就会报错,无法判断要更新那条数据。
  • 解决:暂时没有太好的解决方案,确保唯一即可。
  • 问题2:批量删除插入的数据太多时,SQL报错或者JVM 栈溢出
  • 解决:控制插入list的数量
if (mmOtMapls.size()>0) {
     //为了防止SQL语句超出长度出错,分成几次插入
     if(mmOtMapls.size() <= 1000){
         tbMmOtMaplService.mergeInto(mmOtMapls);
     }else{
         int times = (int)Math.ceil( mmOtMapls.size()/1000.0 );
         for(int i=0; i< times; i++ ){
             tbMmOtMaplService.mergeInto(mmOtMapls.subList(i * 1000, Math.min((i + 1) * 1000, mmOtMapls.size())));
         }
     }
 }

可参考
https://blog.csdn.net/weixin_43303530/article/details/108495327

你可能感兴趣的:(Oracle,sql,java,数据库,oracle)