mybatis批量操作方法

本文介绍如何在Oracle、MSSQL及MySQL中进行批量数据插入与更新操作,并提供MyBatis XML配置示例,包括使用序列、指定数据类型等高级功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

插入数据

SQL语句

oracle :
insert into sss
(
  a,b
)
select '11','aaa' from dual union all
select '22','bbb' from dual 

而在mssql和mysql中是这样的:
insert into sss
(
  a,b
)
values('1','2'),('11','2') 

 

mybatis xml

<!-- 批量插入for Oracle -->
	<insert id="insertBatch4Oracle" parameterType="List">
		insert into aa
		  (
		    a,b
		  )
		  <foreach collection="list" item="item" index="index" separator="union all" >
		  	select  #{item.a},
				#{item.b}
				from dual
		  </foreach>
	</insert>
	
	<!-- 批量插入for Other -->
	<insert id="insertBatch4Other" parameterType="List">
		insert into aa
		  (
		    a,b
		  )
		  VALUES
		  <foreach collection="list" item="obj" index="index" separator="," >
		  (
		  	#{obj.a},#{obj.b}
		  )
		  </foreach>
	</insert>

 

更新数据

SQL语句

update *** set *** where ** in(....) 

 

这种语句  in所在的集合有条数限制 为1000条,当我们在批量更新千条以上数据时就会有问题,解决方法可以分段在执行,1000条记录为一段。 

 

mybatis xml

<update id="updateBatch" parameterType="Map">
		update aa   set 
			a=#{fptm},
			b=#{csoftrain}
		where c in 
		<foreach collection="cs" index="index" item="item" open="("separator=","close=")">
            #{item}
        </foreach>
</update>

 

oracle插入数据时,使用SEQ

mybatis xml

<insert id="insertBatch" parameterType="ArrayList" useGeneratedKeys="true">
    	<selectKey keyProperty="deptno" order="BEFORE" resultType="int">
    		SELECT S_FORUM_USERID.NEXTVAL FROM DUAL
    	</selectKey>
    	
    	INSERT INTO DEPT(DEPTNO , DNAME , LOC) SELECT S_FORUM_USERID.NEXTVAL , A.* FROM (
    	<foreach collection="list" item="item" index="index" separator="UNION">
    		SELECT #{item.dname} , #{item.loc} FROM DUAL
    	</foreach>
    	) A
    </insert>

 

指定数据类型

mybatis xml

<insert id="batchInsertB2B" parameterType="ArrayList">
insert into xxxxtable(hkgs,hkgsjsda,office,asdf,ddd,ffff,supfullName,classtype,agent_type,remark)
<foreach collection="list" item="item" index="index" separator="union all">
select #{item.hkgs,jdbcType=VARCHAR},
#{item.hkgsjsda,jdbcType=VARCHAR},
#{item.office,jdbcType=VARCHAR},
#{item.asdf,jdbcType=VARCHAR},
#{item.ddd,jdbcType=VARCHAR},
#{item.ffff,jdbcType=VARCHAR},
#{item.supfullName,jdbcType=VARCHAR},0,0,
#{item.remark,jdbcType=VARCHAR} from dual
</foreach>
</insert>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值