mybatis执行批量插入insert和批量更新update

Mybatis批量插入和批量更新数据的资料相信大家从网上能查找到很多资料,本文重点总结一下mybatis执行批量插入insert和批量更新update数据。在mysql数据库中批量插入,如:insert into … values (),(),…语法;而在oracle数据库中批量插入如:insert into selcect … union all select …语法。
mysql批量插入

 <insert id="addRoleModule" parameterType="java.util.List">
    INSERT INTO T_P_ROLE_MODULE (ROLE_ID, MODULE_ID)
    VALUES <foreach collection="list" item="item" index="index"  
    separator=",">  
    ( #{item.roleId}, #{item.moduleId})  
    </foreach>  
</insert>

oracle批量插入

<insert id="addRoleModule" parameterType="java.util.List">
    INSERT INTO T_P_ROLE_MODULE (ROLE_ID, MODULE_ID)
    <foreach collection="list" item="item" index="index" separator=" UNION ALL ">  
    SELECT #{item.roleId}, #{item.moduleId} FROM DUAL
    </foreach>  
</insert>

mysql批量更新mysql数据库采用一下写法即可执行,但是数据库连接必须配置:&allowMultiQueries=true,如:jdbc:mysql://blog.yoodb.com:3306/test?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true

<update id="batchUpdate" parameterType="java.util.List">
  <foreach collection="list" item="item" index="index" open="" close="" separator=";">
update test <set> test=${item.test}+1 </set> where id = ${item.id}
 </foreach>
</update>

oracle批量更新

<update id="batchUpdate"  parameterType="java.util.List">
   <foreach collection="list" item="item" index="index" open="begin" close="end;" separator=";">
update test <set> test=${item.test}+1 </set> where id = ${item.id}
   </foreach> 
</update>

Mybatis中sql配置文件属性参数含义说明,参考图:
在这里插入图片描述
对于foreach标签的解释参考了网上的资料,具体如下:foreach的主要用在构建in条件中,它可以在SQL语句中进行迭代一个集合,foreach元素的属性主要有 item,index,collection,open,separator,close。item表示集合中每一个元素进行迭代时的别名,index指定一个名字,用于表示在迭代过程中,每次迭代到的位置,open表示该语句以什么开始,separator表示在每次进行迭代之间以什么符号作为分隔 符,close表示以什么结束,在使用foreach的时候最关键的也是最容易出错的就是collection属性,该属性是必须指定的,但是在不同情况 下,该属性的值是不一样的,主要有一下3种情况:1. 如果传入的是单参数且参数类型是一个List的时候,collection属性值为list2. 如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array3. 如果传入的参数是多个的时候,我们就需要把它们封装成一个Map了,当然单参数也可以封装成map

发布了186 篇原创文章 · 获赞 26 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/G_whang/article/details/104385029
今日推荐