需求背景:项目中频繁使用导入导出功能来录入数据,但是最开始写的是循环insert,性能非常慢,后面考虑优化成了批量提交方式。
在这里我给大家实现了两种数据库的批量插入,因为我们项目是兼容MySQL、Oracle的。
MySQL方式:
<insert id="commonBatchMysqlInsert">
INSERT INTO ${tableName} (
<foreach collection="keys" item="key" separator=",">
${key}
</foreach>
) VALUES
<foreach collection="values" item="list" separator=",">
(
<foreach collection="list" item="item" separator=",">
<choose>
<when test="item.type == 0">
#{item.value}
</when>
<otherwise>
${item.value}
</otherwise>
</choose>
</foreach>
)
</foreach>
</insert>
dao层:
Oracle方式:
<insert id="commonBatchOracleInsert">
INSERT INTO ${tableName} (
<foreach collection="keys" item="key" separator=",">
${key}
</foreach>
)
<foreach collection="values" item="list" separator="union all">
select
<foreach collection="list" item="item" separator=",">
<choose>
<when test="item.type == 0">
#{item.value}
</when>
<when test="item.type == 2">
null
</when>
<otherwise>
${item.value}
</otherwise>
</choose>
</foreach>
from dual
</foreach>
</insert>
dao层:
DataType类,主要是存放当前列信息,之所以加这个是因为Oracle数据库日期类型要加TO_DATE函数,然后日期字段就会设置type值,最后通过if标签判断当前列是${}还是#{}。
注意!!!
我这里的批量插入接口是公共接口,所以我用的是map对象,没有实体类。
题外话:我们这里也实现了批量插入中,如果插入失败的情况下,找到具体哪一条失败,然后将数据写入到Excel文件,提供用户下载,如果有需要可以私信dd我。