最近项目在开发的时候需要导入批量数据,尝试使用批量插入时遇到了几个问题:
1、Oracle批量插入数据的SQL是怎么写的?
2、插入的数据id使用的序列来生成的,如何引入进来?
在网上搜索了资料后找到了相应的解决方法,记录一下,以备不时之需。
1、Oracle批量插入数据库的写法:
<pre name="code" class="html"><insert id="batchInsertAccountInfo" parameterType="java.util.List">
INSERT INTO ACCOUNT_INFO(ID, USERNAME,PASSWORD,GENDER, EMAIL,CREATE_DATE)
(
<foreach collection="list" index="" item="accountInfo" separator="union all">
select
#{accountInfo.id}
#{accountInfo.userName},
#{accountInfo.password},
#{accountInfo.gender},
#{accountInfo.email},
sysdate
from dual
</foreach>
)
</insert>
2、在mybatis中使用序列来生成主键ID:
<insert id="batchInsertAccountInfoUseSeq" parameterType="java.util.List">
<selectKey resultType="long" keyProperty="id" order="BEFORE">
SELECT ACCOUNT_SEQ.NEXTVAL FROM dual
</selectKey>
INSERT INTO ACCOUNT_INFO(ID, USERNAME,PASSWORD,GENDER, EMAIL,CREATE_DATE)
SELECT ACCOUNT_SEQ.NEXTVAL, m.* FROM(
<foreach collection="list" index="" item="accountInfo"
separator="union all">
select
#{accountInfo.userName},
#{accountInfo.password},
#{accountInfo.gender},
#{accountInfo.email},
sysdate
from dual
</foreach>
) m
</insert>
完整项目链接:https://github.com/lanqingchen/oracle