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>
相关推荐
计算机学姐3 小时前
基于微信小程序的旧衣回收系统
java·vue.js·spring boot·微信小程序·小程序·tomcat·mybatis
艾伦~耶格尔12 小时前
Java 之 ssm框架入门
java·开发语言·后端·spring·mybatis·ssm
zxguan12 小时前
Mybatis 学习之 分页实现
学习·mybatis
鱼跃鹰飞16 小时前
大厂面试真题-说一下Mybatis的缓存
java·后端·缓存·面试·职场和发展·mybatis
胡耀超18 小时前
1.分页查询(后端)—— Vue3 + SpringCloud 5 + MyBatisPlus + MySQL 项目系列(基于 Zulu 11)
mysql·spring·spring cloud·mybatis·mybatisplus·zulu11
计算机学姐20 小时前
基于基于微信小程序的社区订餐系统
vue.js·spring boot·后端·微信小程序·小程序·intellij-idea·mybatis
梦城忆1 天前
JPA+Thymeleaf增删改查
ajax·html·mybatis·springboot
码农研究僧1 天前
详细分析Mybatis中的动态Sql(附Demo)
xml·java·数据库·sql·mybatis
计算机学姐1 天前
基于SpringBoot+Vue的旅游攻略平台管理系统
java·vue.js·spring boot·后端·intellij-idea·mybatis·旅游