mybatis 多条update同时执行

本文介绍如何在MyBatis中利用foreach标签实现批量更新操作,通过参数集合和条件判断,动态生成SQL语句,同时讲解了在配置文件中启用多语句执行的方法。

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

想在mapper的一个更新节点进行多条update语句的操作:

<update id="cleanUserByPhone" parameterType="java.lang.String">
  update user set valid_status = 1 where mobile_phone = #{mobilePhone};
  update user_account set valid_status = 1 where mobile_phone = #{mobilePhone} ;
</update>

foreach 方式断句,用分号分隔每个update语句,注意<> 等需要转义的符号

<update id="updateMore" parameterType="java.util.List">
        <foreach collection="articleList" item="item" index="index" open="" close="" separator=";">
            update article
            <set>
                <if test="item.contentAuthor != null">content_author = #{item.contentAuthor}, </if>
                <if test="item.contentTitle != null">content_title = #{item.contentTitle}, </if>
                <if test="item.contentLink != null"> content_link = #{item.contentLink}, </if>
                update_date = #{item.updateDate}
            </set>
            where article_id = #{item.articleId} and staff_id = #{item.staffId} and status &lt; 5
        </foreach>
    </update>

 

mybatis是默认不支持多条语句拼接插入或更新的,需要在数据库配置中配置相关参数  以允许使用分号分隔sql语句:

propertes 或者yml配置 文件中的jdbc后追加&allowMultiQueries=true​​​​​​​

application-prod.yml 数据源配置参考

spring:
    # 数据源配置
    datasource:
        type: com.alibaba.druid.pool.DruidDataSource
        driverClassName: com.mysql.cj.jdbc.Driver
        druid:
            # 主库数据源
            master: #localhost
                url: jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
                username: root
                password: aaaa@123

参考:

springboot+Mybatis+MySql 一个update标签中执行多条update sql语句_yjl33的博客-优快云博客

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值