这篇文章主要讲述Mybatis当中针对于Mysql和orcle数据库批量新增的做法,写的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧。
首先有关于批量新增大部分都会使用到foreach标签,所以写批量的时候我们要了解foreach当中的属性作用。在这里我列出foreach的属性作用,帮助大家回顾一下。
foreach标签
foreach一共有六个属性:
collection:指定要遍历的集合:list类型的参数会特殊处理封装在map中,map的key就叫list
item:将当前遍历出的元素赋值给指定的变量
separator:每个元素之间的分隔符
open:遍历出所有结果拼接一个开始的字符
close:遍历出所有结果拼接一个结束的字符
index:索引。遍历list的时候是index就是索引,item就是当前值
遍历map的时候index表示的就是map的key,item就是map的值
由于mysql和oracle数据库语法略有差异,所以这里分别列出针对于两个不同的批量该如何写
Mysql当中如何做?
第一种写法
Mysql是支持这种语法的,而oracle是不支持的。
insert into tbl_employee( last_name,email,gender,d_id ) values (?,?,?,?) , (?,?,?,?)
<insert id="addEmps">
insert into tbl_employee(
<include refid="insertColumn"></include>
)
values
<foreach collection="emps" item="emp" separator=",">
(#{emp.lastName},#{emp.email},#{emp.gender},#{emp.dept.id})
</foreach>
</insert>
第二种写法
这种方式需要数据库连接属性allowMultiQueries=true;
这种分号分隔多个sql可以用于其他的批量操作(删除,修改)
jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true
<insert id="addEmps">
<foreach collection="emps" item="emp" separator=";">
insert into tbl_employee(last_name,email,gender,d_id)
values(#{emp.lastName},#{emp.email},#{emp.gender},#{emp.dept.id})
</foreach>
</insert>
Oracle当中如何做?
Oracle不支持values(),(),()
Oracle支持的批量方式
第一种写法
oracle在数据库当中虽然支持多条新增语句一起执行,但是在mybatis当中我们会发现他会报无效字符。所以我们得加上begin 和 end便可避免这种问题。
begin
insert into employees(employee_id,last_name,email)
values(employees_seq.nextval,'test_001','test_001');
insert into employees(employee_id,last_name,email)
values(employees_seq.nextval,'test_002','test_002');
end;
映射文件写法。
<insert id="addEmps" databaseId="oracle">
<foreach collection="emps" item="emp" open="begin" close="end;">
insert into employees(id,last_name,email)
values(employees_seq.nextval,#{emp.lastName},#{emp.email});
</foreach>
</insert>
第二种写法
oracle是支持这种语法的sql的,两个表互相导入的话,就可以用这种写法。所以我们可以创建临时表来通过这种语法完成批量新增。
insert into 表1(列名1,列名2,.....) select 列名1,列名2,.....from 表2
使用union来串联起来多行数据,当做临时表
insert into employees(employee_id,last_name,email)
select employees_seq.nextval,lastName,email from(
select 'test_a_01' lastName,'test_a_e01' email from dual
union
select 'test_a_02' lastName,'test_a_e02' email from dual
union
select 'test_a_03' lastName,'test_a_e03' email from dual
)
xml映射文件写法
<insert id="addEmps" databaseId="oracle">
insert into employees(
id,last_name,email
)
<foreach collection="emps" item="emp" separator="union"
open="select employees_seq.nextval,lastName,email from("
close=")">
select #{emp.lastName} lastName,#{emp.email} email from dual
</foreach>
</insert>
总结
相对来说写的还算凑合,感觉小编整理的还可以的,确实您也学到了,麻烦帮小编点个关注或者点个赞,哈哈哈