作者:colin0702
链接:mybatis批量插入oracle并返回主建ID
来源:csdn
转载的话:找了很多,这是唯一可行的方案,批量插入返回主键,然后把主键用于别的地方,因为是批量插入,所以转为如果一条一条插入的话是不合理的,所以我们先成批获取到sequnece的nextval,再进行插入操作,分开两次进行就可以了,第一次获取时其它的列是要插入的列,第二次把第一次的结果批量insert,select就可以了,注意使用union all进行连接
很多时候我们都需要对数据进行批量插入,然后希望返回对应的主建ID,以便执行后续逻辑。如果是mysql数据库,mybatis有很好的支持,这种例子网上很多,此处不再赘述。今天我们主要探讨的是关于mybatis操作oracle数据库时,如何实现批量插入并返回主建ID,当然,此处的主建ID一般使用的是oracle的序列生成的。
之前晚上搜索了很多oracle批量插入的例子,但是都无法将主建ID返回,多次尝试后发现oracle批量插入有一个特性:可以将查询到的集合插入至表中,也就是使用insert into select的语法。既然mybatis不支持在一条insert into select 语句中把主建ID返回,那就把这个语句拆分成2块:
1、先使用select语句,把生成的主建ID及待插入的数据组成的集合返回
2、将1返回的集合使用insert into select 直接插入
<!-- 获取待插入集合包含主建ID -->
<select id="initInsertBatch" parameterType="com.xxx.base.user.srv.entity.po.BaseUserPO" resultMap="baseUserResult">
select ID_USER.nextval as userid, t.* from (
<foreach collection="list" index="index" item="info" separator="union all">
select
#{info.username} as username,
#{info.password} as password
from dual
</foreach>
)t
</select>
此集合返回的数据中就已经存在了我们想要返回的主建ID,后续代码直接使用即可,注意:将字段进行重命名,使之与实体映射相匹配,如上述中的userid,username,password
<!-- 插入待插入集合包含主建ID -->
<insert id="insertBatch" parameterType="com.xxx.base.user.srv.entity.po.BaseUserPO">
INSERT INTO BASE_USER
select * from (
<foreach collection="list" index="index" item="info" separator="union all">
select
#{info.userid},
#{info.username},
#{info.password}
from dual
</foreach>
)t
</insert>
此步骤就是常规的一个批量插入
由此,我们便实现了mybatis操作oracle完成数据批量插入并返回主建ID这一需求
亲爱的读者:有时间可以点赞评论一下
月份 | 原创文章数 |
---|---|
202204 | 1 |
202203 | 11 |
202201 | 2 |
202108 | 7 |
202107 | 3 |
202106 | 16 |
202105 | 10 |
202104 | 16 |
202103 | 56 |
202102 | 14 |
202010 | 3 |
202009 | 3 |
202008 | 7 |
202007 | 7 |
202006 | 10 |
202005 | 11 |
202004 | 22 |
202003 | 52 |
202002 | 44 |
202001 | 83 |
201912 | 52 |
201911 | 29 |
201910 | 41 |
201909 | 99 |
201908 | 35 |
201907 | 73 |
201906 | 121 |
201811 | 1 |
201810 | 2 |
201804 | 1 |
201803 | 1 |
201802 | 1 |
201707 | 1 |
全部评论