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>
相关推荐
涵涵(互关)5 小时前
Maven多模块项目MyMetaObjectHandler自动填充日期未生效
spring·maven·mybatis
ss27312 小时前
手写MyBatis第96弹:异常断点精准捕获MyBatis深层BUG
java·开发语言·bug·mybatis
lang2015092814 小时前
MyBatis配置全解析:核心要点详解
mybatis
yunmi_18 小时前
安全框架 SpringSecurity 入门(超详细,IDEA2024)
java·spring boot·spring·junit·maven·mybatis·spring security
wuxuanok18 小时前
苍穹外卖 —— 公共字段填充
java·开发语言·spring boot·spring·mybatis
伯明翰java20 小时前
mybatis-generator插件自动生成mapper及其实体模型配置
java·开发语言·mybatis
简色1 天前
题库批量(文件)导入的全链路优化实践
java·数据库·mysql·mybatis·java-rabbitmq
lunzi_fly2 天前
【源码解读之 Mybatis】【核心篇】--第5篇:Executor执行器体系详解
mybatis
韩立学长2 天前
【开题答辩实录分享】以《走失人口系统档案的设计与实现》为例进行答辩实录分享
mysql·mybatis·springboot
Flash Dog2 天前
【MyBatis】——执行过程
java·mybatis