Mysql与Oracle中批量插入和更新区别

本文详细介绍了在Mysql和Oracle数据库中进行批量Update、Insert和Select操作的方法。通过使用MyBatis框架,可以有效地提高数据处理效率,包括批量更新、批量插入和批量选择数据的具体实现。

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

引言

数据库的不同,决定了批量更新语句的差别!

批量 Update

  • Mysql
<update id="updateSomething" parameterType="java.util.List">
    update userTable
         <foreach collection="list" item="user" index="index">
             <if test="user.status !=null and user.status != -1">
                 when id=#{user.id} then #{user.status}
             </if>
             <if test="user.status == null or user.status == -1">
                 when id=#{user.id} 
             </if>
         </foreach>
    where id in
    <foreach collection="list" index="index" item="item" separator="," open="(" close=")">
        #{item.id}
    </foreach>
</update>
  • Oracle
参数类型:List\<User> users 

<update id="updateSomething" parameterTye="com.alibaba.User">
	<foreach collection="list" item="user" open="begin" searator=";" close=";end;">
		update userTable set id = #{user.id}
		where
		<choose>
			<when test = "user.age == null or user.age == ''">
				name = #{user.name}
			</when>
			<otherwise>
				name = #{user.name} and age = #{user.age}
			</otherwise>
	</foreach>
</update> 

注意:获取参数时都要带上user变量,如#{user.xxx}

批量 Insert

  • Mysql
    如果你的数据库还支持多行插入, 你也可以传入一个 Author 数组或集合,并返回自动生成的主键。
<insert id="insertAuthor" useGeneratedKeys="true"
    keyProperty="id">
  insert into Author (username, password, email, bio) values
  <foreach item="item" collection="list" separator=",">
    (#{item.username}, #{item.password}, #{item.email}, #{item.bio})
  </foreach>
</insert>

对于不支持自动生成类型的数据库或可能不支持自动生成主键的 JDBC 驱动,MyBatis 有另外一种方法来生成主键。

这里有一个简单(甚至很傻)的示例,它可以生成一个随机 ID(你最好不要这么做,但这里展示了 MyBatis 处理问题的灵活性及其所关心的广度):

  • Oracle
<insert id="insertAuthor">
  <selectKey keyProperty="id" resultType="int" order="BEFORE">
    select CAST(RANDOM()*1000000 as INTEGER) a from SYSIBM.SYSDUMMY1
  </selectKey>
  insert into Author
    (id, username, password, email,bio, favourite_section)
  values
    (#{id}, #{username}, #{password}, #{email}, #{bio}, #{favouriteSection,jdbcType=VARCHAR})
</insert>

批量 Select

  • Mysql
  • Oracle
参数类型:List\<User> users 

<select id="selectSomething" resultType="hashmap">
	select  * from
	where id in
	<foreach collection="users" item="user" open="(" searator="," close=")">
		#{user.id}
	</foreach>
</select>

参考文献

MyBatis 3 中文文档

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值