MyBatis批量更新

问题:在项目中遇到需要同时更新字典表多个键的值,而字典表中多个键是由同一个字段保存的,问题就变成了如何根据同一个字段的不同属性更新对应的值,解决方法如下。

1.一次执行多条sql语句

需要在jdbc添加中allowMultiQueries=true
jdbc.jdbcUrl=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true
然后就可以在mapper映射文件中在同一个方法中写多条sql语句,多条sql语句中间用分号隔开

比如:
<update id="updateState">  
    update td_examinfo set exam_state=2 where now() > exam_examStartTime and exam_examEndTime > now();  
    update td_examinfo set exam_state=3 where now() > exam_examEndTime  
 </update>  

经测试,方法的执行结果取决于多条sql执行结果的逻辑与,即有一条失败方法执行失败,但执行成功的并不会做回滚操作,所以这种方法不具备事务属性。

2.使用case when then end

    <update id="updateValuesBykeys" parameterType="com.haha.TestDto">
        UPDATE dict SET `value` = CASE
        <if test="freeCount != null">
            WHEN `key` = 'free_count' THEN #{freeCount}
        </if>
        <if test="rate != null">
            WHEN `key` = 'rate' THEN #{rate}
        </if>
        <if test="singleMin != null">
            WHEN `key` = 'single_min' THEN #{singleMin}
        </if>
        <if test="singleMax != null">
            WHEN `key` = 'single_max' THEN #{singleMax}
        </if>
        <if test="freeCount != null or rate != null or singleMin != null or singleMax != null">
            END
        </if>
        where `key` IN ('free_count','rate','single_min','single_max')
    </update>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值