批量插入
批量插入mysql和oracle的sql会有些差别,要注意!
mysql:
<insert id="batchInsert" parameterType="java.util.List">
insert into user(username, password) values
<foreach collection="list" item="item" index="index"
separator=",">
(#{item.username},
#{item.password} )
</foreach>
</insert>
oracle:
<insert id="batchInsert" parameterType="java.util.List">
insert into user(username, password)
<foreach close=")" collection="list" item="item" index="index" open="(" separator="union">
select
#{item.username,jdbcType=VARCHAR},
#{item.password,jdbcType=VARCHAR}
from dual
</foreach>
</insert>
下面的是Oracle使用 Sequence来生成主键的批量插入写法
<insert id="batchInsert" parameterType="java.util.List">
insert into user(id, username, password)
select SEQ_USER_ID.NEXTVAL,T.* from(
<foreach collection="list" item="item" index="index"
separator="UNION">
SELECT
#{item.username,jdbcType=VARCHAR},
#{item.password,jdbcType=VARCHAR}
from dual
</foreach>
) T
</insert>
批量删除
<delete id="batchDeleteByIdList" parameterType="java.util.List">
delete from user
where id in
<foreach item="id" collection="list" open="(" separator="," close=")">
#{id}
</foreach>
</delete>
当然,也可以使用Array来替代List,修改parameterType=“array”和collection=”array”即可
本文介绍了如何在MySQL和Oracle中进行批量插入和批量删除操作,并详细展示了使用MyBatis框架时的具体SQL语句。针对Oracle数据库还提供了使用Sequence生成主键的批量插入方法。
1万+

被折叠的 条评论
为什么被折叠?



