mybatis批量操作方法

插入数据

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>

 

猜你喜欢

转载自billmingchen.iteye.com/blog/1920834