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

foreach标签简介

实践

demo1

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

xml 复制代码
<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类型的

xml 复制代码
  <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

xml 复制代码
 <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>
相关推荐
菜鸟蹦迪11 小时前
学习记录:mybatis和jdbc实现数据表作为参数的相关的sql操作
sql·学习·mybatis
芯眼2 天前
STM32启动文件详解(重点)
java·开发语言·c++·stm32·单片机·mybatis
遗憾皆是温柔2 天前
MyBatis—动态 SQL
java·数据库·ide·sql·mybatis
CircleMouse3 天前
springboot如何通过提供的注解方式来操作Redis
java·spring boot·redis·spring·mybatis
荔枝吻3 天前
【抽丝剥茧知识讲解】引入mybtis-plus后,mapper实现方式
java·sql·mybatis
Allen Bright4 天前
【MyBatis-9】MyBatis分页插件PageHelper深度解析与实践指南
mybatis
柴薪之王、睥睨众生4 天前
(自用)Java学习-5.8(总结,springboot)
java·开发语言·spring boot·学习·mybatis
唐僧洗头爱飘柔95274 天前
【SSM-SSM整合】将Spring、SpringMVC、Mybatis三者进行整合;本文阐述了几个核心原理知识点,附带对应的源码以及描述解析
java·spring·mybatis·springmvc·动态代理·ioc容器·视图控制器
意倾城5 天前
浅说MyBatis-Plus 的 saveBatch 方法
java·mybatis