欢迎访问WDPHP素材源码!今天是2024年04月28日 星期日,傍晚好!下班了!
您好,游客 [ 马上登录 | 注册帐号 | 微信登录 | QQ登录]
当前位置:首页 > 教程 > 其他教程 > 

Mybatis执行多条语句/批量更新的方法是什么
栏目分类:其他教程    发布日期:2023-09-10    浏览次数:248次     收藏

本篇内容主要讲解“Mybatis执行多条语句/批量更新的方法是什么”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Mybatis执行多条语句/批量更新的方法是什么”吧!

    Mybatis执行多条语句/批量更新

    Mybatis实现多条语句

    通常用在删除主表信息同时删除子表信息。

    如果利用多次Dao进行执行sql,程序就写起来麻烦并且阅读难度会提升。

    (删除income表中的信息,同时删除子表income_detail表中的相关信息)

    delete from income_detail where income_id=#{id}; 
    delete from income where id=#{id};

    或者是批量更新,比如利用foreach批量update多条数据。

    <update id="update">
        <foreach collection="xxList" item="item" index="index" open="" close="" separator=";">
          update t_xxx
          <set>
            xxx = #{item.xxx}
          </set>
          where id = #{item.id}
        </foreach>
    </update>

    这些语句的类似点在于都是在mybatis中带有分号的多条sql。

    而直接执行又会报错,所以我们需要在jdbc连接中加上allowMultiQueries参数,设置为true。

    <property name="url" value="jdbc:mysql://localhost:3306/amoeba?characterEncoding=UTF-8&allowMultiQueries=true"/>
    jdbc.url=jdbc:mysql://localhost:3306/amoeba?characterEncoding=UTF-8&allowMultiQueries=true

    Mybatis同时执行多条语句

    有个常见的场景:删除用户的时候需要先删除用户的外键关联数据,否则会触发规则报错。

    解决办法不外乎有三个

    • 1、多条sql分批执行

    • 2、存储过程或函数调用

    • 3、sql批量执行

    今天我要说的是MyBatis中如何一次执行多条语句(使用mysql数据库)。

    1、修改数据库连接参数加上allowMultiQueries=true,如:

    hikariConfig.security.jdbcUrl=jdbc:mysql://xx.xx.xx:3306/xxxxx?characterEncoding=utf-8&autoReconnect=true&failOverReadOnly=false&allowMultiQueries=true

    2、直接写多条语句,用“;”隔开即可

    <delete id="deleteUserById" parameterType="String">
        delete from sec_user_role where userId=#{id};
        delete from sec_user where id=#{id};
    </delete>
    源码 模板 特效 素材 资源 教程 站长