注:使用批量插入或更新容易导致锁表,如果是读取频率很高的表还是不推荐使用
mysql版请参照此文章:https://blog.csdn.net/weixin_43303530/article/details/121536205
为了不影响程序性能,想要将一批数据批量加入到oracle,但是有些数据在新增的同时又需要判断是否存在与该数据用户账号和用户部门相同的数据,如果存在,就只对该数据进行更新,而不新增,如果不存在,就新增。
注:这里使用的持久层框架为ibatis
为了实现该功能,需要用到oracle的merge into语法:
注意:
-
使用该语法时,无论是update还是insert后面都不需要加表名去声明,且insert后面也不需要加into,不然就会报错,缺少关键字:
-
在insert后面的所需增加的字段名也不需要采用:表名.字段名的形式,直接用小括号将字段名扩起来就可以了;
-
在insert的时候values后面的值,一定要采用:表名.字段名的形式,否则会报列无效:
-
如果报错标识符无效,需要使用as起别名:
-
如果只有一条数据,迭代器迭代的时候conjunction属性为""并不会影响程序运行,但是数据在两条及两条以上,需要设置该属性为conjunction=“union”,否则会报错:
完整Mapper映射:
Mapper.xml:
<statement id="insertSysDayClicks" parameterClass="java.util.List">
merge into sys_day_click u
using
(
<iterate conjunction="union">
select #List[].usercode# as usercode,#List[].username# as username,#List[].usertype# as usertype,
#List[].deptcode# as deptcode,#List[].stime# as stime,#List[].clickcount# as clickcount from dual
</iterate>
) t
on (u.usercode = t.usercode and u.stime = t.stime and u.deptcode = t.deptcode)
when matched then
update set u.clickcount = t.clickcount
when not matched then
insert (usercode, username, usertype, deptcode, stime, clickcount) VALUES(t.usercode, t.username, t.usertype, t.deptcode, t.stime, t.clickcount)
</statement>
Mapper.java:
@Override
public int insertSysDayClicks(List<HashMap> dayCountEntityList) {
this.getSqlMapClientTemplate().queryForObject("insertSysDayClicks", dayCountEntityList);
return Constants.CODE_DAO_SUCCESS; //返回的状态值
}
该Mapper.xml的映射标签不可以写成insert,会报错:
如果需要使用insert标签,需要改写Mapper.java:
public int insertSysDayClicks(List<HashMap> dayCountEntityList) {
this.getSqlMapClientTemplate().insert("insertSysDayClicks", dayCountEntityList);
return Constants.CODE_DAO_SUCCESS;
}
参考博文:
- https://www.cnblogs.com/wuxun1997/p/6602202.html
- https://blog.csdn.net/qincidong/article/details/40431625
- https://www.cnblogs.com/kongxc/p/9237941.html
- https://blog.csdn.net/tianwailaibin/article/details/8249663
- https://blog.csdn.net/xingjianwu/article/details/81455776
- https://blog.csdn.net/hong10086/article/details/54342819