最近看一个老项目,使用的Oracle数据库,发现要使用MyBatis执行批量操作还是不太一样。
下面我们来看一下,Oracle数据库,如何使用MyBatis来批量插入和更新。
批量插入
因为Oracle和MySQL的insert还不太一样,Oracle不能像MySQL直接语法插入多条:
INSERT INTO table_name(column1, column2, column3)
VALUES
(value1, value2, value3),
(value4, value5, value6),
(value7, value8, value9);
所以需要使用insert all来变通一下:
insert allinto table_name values(1,'张三',49)into table_name values(2,'李四',39)into table_name values(3,'王五',29)into table_name values(4,'赵六',19)into table_name values(5,'孙七',59)
select 1 from dual;
上面的table_name可以是不同的表。
简单来说就是把插入语句放在insert all和select 1 from dual;之间
注意中间的插入语句没有insert
在MyBatis中我们使用foreach拼装一下,open就是insert all,中间是into 插入语句,close是select 1 from dual
注意最后没有分号,除非你url中设置了allowMultiQueries=true才可以带分号结尾,否则MyBatis执行会出错。
下面是具体的示例:
<insert id="insertSelectiveList" parameterType="vip.meet.BusinessDateType"><foreach collection="list" item="item" index="index" separator="" open="insert all" close="select 1 from dual">into business_date_type<trim prefix="(" suffix=")" suffixOverrides=","><if test="item.pkId != null">PK_ID,</if><if test="item.fid != null">FID,</if><if test="item.rowIndex != null">ROW_INDEX,</if><if test="item.dataType != null">DATA_TYPE,</if><if test="item.lastModifyTime != null">LAST_MODIFY_TIME,</if></trim><trim prefix="values (" suffix=")" suffixOverrides=","><if test="item.pkId != null">#{item.pkId,jdbcType=NUMERIC},</if><if test="item.fid != null">#{item.fid,jdbcType=NUMERIC},</if><if test="item.rowIndex != null">#{item.rowIndex,jdbcType=NUMERIC},</if><if test="item.dataType != null">#{item.dataType,jdbcType=NUMERIC},</if><if test="item.lastModifyTime != null">#{item.lastModifyTime},</if></trim></foreach>
</insert>
批量更新
Oracle没有批量更新的语句,怎么批量更新呢?
可以使用begin,end语句块,可以把update语句放在begin和end之间执行。
BEGINUPDATE business_date_type SET price = 2.99 WHERE FID = 27210303266880;UPDATE business_date_type SET price = 4197276.99 WHERE FID = 27210303266880;
END;
在MyBatis中我们使用foreach拼装一下,open就是begin,中间是update语句,close是;end;
close为啥是;end;呢,因为foreach的separator最后一个语句不会添加,所以少一个,需要补一个。
end后面的分号(;)是因为begin end;语法,这个分号不能省略,必须添加。
为什么有的不能有分号,有分号出错,begin end又必须有分号,没有分号出错呢?
我想大概是因为,其他都是一个完整语句,begin end是一个语句块,可能有多条语句,必须通过分号(;)来判断结束吧。
<update id="updateList" parameterType="java.util.List"><foreach collection="list" item="item" index="index" open="begin" close=";end;" separator=";">update business_date_type<set><if test="item.dataType != null">DATA_TYPE = #{item.dataType,jdbcType=VARCHAR},</if><if test="item.lastModifyTime != null">LAST_MODIFY_TIME = #{item.lastModifyTime},</if></set>where FID = #{item.fid,jdbcType=NUMERIC}</foreach>
</update>