java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > mybatis使用case when按照条件更新

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

作者:linab112

示例一通过条码批量更新入库和剩余数量,直接高效;示例二使用set和trim标签,实现动态字段更新与条件优化,结构更复杂但灵活性更高

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标签,感觉更为复杂。

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文