欢迎来到徐庆高(Tea)的个人博客网站
磨难很爱我,一度将我连根拔起。从惊慌失措到心力交瘁,我孤身一人,但并不孤独无依。依赖那些依赖我的人,信任那些信任我的人,帮助那些给予我帮助的人。如果我愿意,可以分裂成无数面镜子,让他们看见我,就像看见自己。察言观色和模仿学习是我的领域。像每个深受创伤的人那样,最终,我学会了随遇而安。
当前位置: 日志文章 > 详细内容

mybatis使用case when按照条件进行更新方式

2025年08月23日 Java
mybatis使用case when按照条件更新示例代码<update id="updatenrpurchaseorderdetailbygoodsbarcode"> update

mybatis使用case when按照条件更新

示例代码

<update id="updatenrpurchaseorderdetailbygoodsbarcode">
    update nr_purchase_order_detail
    set stored_num =
    <foreach collection="barcodelist" item="item" index="index"
             separator=" " open="case goods_barcode" close="end">
        when #{item.barcode} then stored_num + #{item.receivenum}
    </foreach>
    ,unstored_num =
    <foreach collection="barcodelist" item="item" index="index"
             separator=" " open="case goods_barcode" close="end">
        when #{item.barcode} then actual_goods_num - stored_num
    </foreach>
    where goods_barcode in
    <foreach collection="barcodelist" item="item" index="index" separator="," open="(" close=")">
        #{item.barcode}
    </foreach>
    and parent_id = #{id}
</update>
<!--casewhen形式更新-->
<update id="testcasewhen" parametertype="java.util.map">
    update ${user}
    <set>
        <trim prefix="id= case id" suffix="end,">
            <foreach collection="list" item="param">
                <if test="param.id != null and id != ''">
                    when #{param.id} then #{param.id}
                </if>
            </foreach>
        </trim>
        <trim prefix="username = case id" suffix="end,">
            <foreach collection="list" item="param">
                <if test="param.username != null and param.username != ''">
                    when #{param.} then #{param.username}
                </if>
            </foreach>
        </trim>
        <trim prefix="password = case id" suffix="end,">
            <foreach collection="list" item="param">
                <if test="param.password != null and param.password != ''">
                    when #{param.id} then #{param.password}
                </if>
            </foreach>
        </trim>
    </set>
    <where>
        id in
        <foreach collection="list" item="param" separator="," open="(" close=")">
            #{param.id}
        </foreach>
    </where>
</update>

说明

上述第一个示例中,按照条码进行批量更新,将所有的条码对应的入库数量和剩余数量进行更新。

第二个示例中,又使用了set标签和trim标签,感觉更为复杂。

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。