oracle :
insert into sss
(
a,b
)
select '11','aaa' from dual union all
select '22','bbb' from dual
而在mssql和mysql中是这样的:
insert into sss
(
a,b
)
values('1','2'),('11','2')
所有就使用foreach时有一些区别:
例如下
<!-- 批量插入for Oracle -->
<insert id="insertBatch4Oracle" parameterType="List">
insert into aa
(
a,b
)
<foreach collection="list" item="item" index="index" separator="union all" >
select #{item.a},
#{item.b}
from dual
</foreach>
</insert>
<!-- 批量插入for Other -->
<insert id="insertBatch4Other" parameterType="List">
insert into aa
(
a,b
)
VALUES
<foreach collection="list" item="obj" index="index" separator="," >
(
#{obj.a},#{obj.b}
)
</foreach>
</insert>
还有一个批量更新的问题,oracle中 形如 update *** set *** where ** in(....)
这种语句 in所在的集合有条数限制 为1000条,当我们在批量更新千条以上数据时就会有问题,解决方法可以分段在执行,1000条记录为一段。
<update id="updateBatch" parameterType="Map">
update aa set
a=#{fptm},
b=#{csoftrain}
where c in
<foreach collection="cs" index="index" item="item" open="("separator=","close=")">
#{item}
</foreach>
</update>
java代码:
public int updateBatch(BB b, List<String> SS) {
int count = 0;
int len = (SS.size() + 999) / 1000;
List<List<String>> a = new ArrayList<List<String>>();
for (int i = 0; i < len; i++) {
a.add(new ArrayList<String>());
}
for (int i = 0; i < len - 1; i++) {
for (int j = 0; j < 1000; j++) {
a.get(i).add(SS.get((i * 1000) + j));
}
}
for (int i = 0; i < SS.size() % 1000; i++) {
a.get(len - 1).add(SS.get(((len - 1) * 1000) + i));
}
for (int i = 0; i < a.size(); i++) {
Map pM = BeanUtils.describe(rp);
pM.put("SS", a.get(i));
this.getSqlSessionTemplate().update(MAPPER_NS + "updateBatch",
pM);
count += a.get(i).size();
}// 分段批量更新
return count;
}