MyBatis<foreach>标签的用法与实践

foreach标签简介

在这里插入图片描述

实践

demo1
简单的一个批量更新,这里传入了一个List类型的集合作为参数,拼接到 in 的后面 ,来实现一个简单的批量更新

<update id="updateVislxble" parameterType="java.util.List">
        update models set visible =0
        where llm_id
        IN
        <foreach collection="allVisible" item="visible" open="(" separator="," close=")">
            #{visible}
        </foreach>
    </update>
  • collection=“allVisible”,allVisible代表传入的集合
  • item=“visible” ,visible代表集合的每一个元素
  • open=“(” 代表以( 开头
  • separator=“,” 代表以“,”分隔,
  • close=“)” 代表以“)”结束

本质上这里是个拼接,所有要保证这里list不为空,不然会报错

demo2
这里还是个批量更新,但是传入的参数多了起来,这里是的入参是个map,并且里面这个status是一个List类型的

  <select id="getModelEvaluateTaskPage" parameterType="java.util.Map" resultType="com.test.test">
        select * from evaluate_tasks t
        <where>
            <if test="status !=null">
                and  t.status  in
                <foreach item="item" index="index" collection="status"
                         open="(" separator="," close=")">
                    #{item}
                </foreach>
            </if>
            <if test="taskName !=null and taskName!=''">
                and  t.task_name like concat('%',#{taskName},'%')
            </if>
            <if test="startTime !=null and endTime!=null">
                and  t.created_time between #{startTime} and #{endTime}
            </if>
            and t.user_id = #{userId}
        </where>
        order by t.created_time ${sort}
    </select>

demo3
这里的场景传入了一个list,里面是多个对象,根据对象的属性A去更新属性B,这里额外使用了 case when then

 <update id="bitchUpdateStatueById" parameterType="java.util.List">
        UPDATE evaluate_tasks
        SET status = CASE service_name
        <foreach collection="updates" item="update" separator=" ">
            WHEN #{update.serviceName} THEN #{update.status}
        </foreach>
        END,
        updated_time = CASE service_name
        <foreach collection="updates" item="update" separator=" ">
            WHEN #{update.serviceName} THEN #{update.endTime}
        </foreach>
        END
        WHERE service_name IN
        <foreach collection="updates" item="update" open="(" separator="," close=")">
            #{update.serviceName}
        </foreach>
    </update>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值