mybatis同时向Oracle插入一条或多条数据

导读:本篇文章讲解 mybatis同时向Oracle插入一条或多条数据,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

1、在MySQL中

可以使用insert语句,直接插入多条数据,多组数据之间用逗号隔开

SQL格式:

insert into 表名(字段1,字段2) values(值1,值2) , (值3,值4)

mybatis中的写法【已学生表为例】:

<!-- list是一个存储student数据的集合-->
<insert id="方法名">
	insert into student(id, name) values
	<foreach item="item" index="index" collection="list" separator=",">
		(#{item.id},#{item.name})
	</foreach>
</insert>

2、在Oracle中

Oracle不能直接使用insert into语句同时插入多条数据

可以使用以下两种方法,同时插入多条数据

2.1、insert all方式

SQL格式:

INSERT ALL
	INTO 表名(字段1,字段2) VALUES(值1,值2)
	INTO 表名(字段1,字段2) VALUES(值①,值②)
	INTO 表名(字段1,字段2) VALUES(值Ⅰ,值Ⅱ)
SELECT * FROM dual
--dual是一个不存在的表(自定义的表名)

已student表为例,SQL添加三条数据

INSERT ALL
	INTO student(id,name) VALUES(1001,'张三')
	INTO student(id,name) VALUES(1002,'李四')
	INTO student(id,name) VALUES(1003,'王五')
SELECT * FROM dual
--dual是一个不存在的表(自定义的表名)

mybatis中的写法

<!-- list时存储student信息的集合 -->
<insert id="方法名" parameterType="java.util.List">
	INSERT ALL 
	<foreach collection="list" index="index" item="item">
		INTO 
		student (id, name) 
		VALUES
		(#{item.id},#{item.name})
	</foreach>
	select * from dual
</insert>

2.2、insert into方式【需要别名,union all语句】

SQL格式:

Insert into 表名 表的别名(字段1, 字段2) 
select * from (
select 值1, 值2 from dual union all
select 值①, 值② from dual union all
select 值Ⅰ,  值Ⅱ from dual
)
--dual是一个不存在的表(自定义的表名)

已student表为例,SQL添加三条数据

Insert into student s(id, name) 
select * from (
select 1001, '张三' from dual union all
select 1002, '李四' from dual union all
select 1003, '王五' from dual
)
--dual是一个不存在的表(自定义的表名)

mybatis中的写法

<!-- list时存储student信息的集合 -->
<insert id="方法名" parameterType="java.util.List">
	Insert into student s(id, name) 
        select * from ( 
	        <foreach collection="list" index="index" item="item" separator="union all">
		        select (#{item.id},#{item.name}) from dual 
	        </foreach>
        )
        --dual是一个不存在的表(自定义的表名)
</insert>

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/99594.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!