Mybatis 动态 SQL - foreach

动态SQL的另一个常见需求是需要迭代一个集合,通常用于构建IN条件。例如:

XML 复制代码
<select id="selectPostIn" resultType="domain.blog.Post">
  SELECT *
  FROM POST P
  <where>
    <foreach item="item" index="index" collection="list"
        open="ID in (" separator="," close=")" nullable="true">
          #{item}
    </foreach>
  </where>
</select>

​<foreach>​元素非常强大,它允许您指定一个集合,并声明在元素体内可用的item和index变量。它还允许您指定打开和关闭字符串,并添加一个分隔符放置在迭代之间。该元素非常智能,不会意外地附加额外的分隔符。

注意:您可以将任何可迭代对象(例如List、Set等)、任何Map对象或数组对象作为 ​<foreach>​元素的collection参数传递。当使用可迭代对象或数组时,index表示当前迭代的次数,而value item表示在此迭代中检索到的元素。当使用Map(或包含Map.Entry对象的Collection)时,index表示键对象,item表示值对象。

相关推荐
Don.TIk3 小时前
ChapterOne-搭建项目骨架
java·spring·spring cloud·mybatis
南极企鹅3 小时前
事务&@Transactional注解
java·数据库·spring·oracle·mybatis
隐退山林9 小时前
JavaEE进阶:MyBatis 操作数据库(入门)
数据库·java-ee·mybatis
Devin~Y11 小时前
互联网大厂 Java 面试实录:JVM、Spring Boot、MyBatis、Redis、Kafka、Spring AI、K8s 全链路追问小Y
java·jvm·spring boot·redis·kafka·mybatis·spring security
码云骑士1 天前
MyBatis-Plus从入门到实战,Lambda查询+注解配置+SpringBoot整合全解析
mybatis
IronMurphy1 天前
Redis拷打第六讲
redis·spring·mybatis
那个失眠的夜1 天前
SpringBoot
java·开发语言·spring boot·spring·mvc·mybatis
接着奏乐接着舞1 天前
springboot mybatis
spring·tomcat·mybatis
Devin~Y2 天前
大厂Java面试实录:Spring Boot/Cloud、JVM、Redis、Kafka、MyBatis 到 RAG/Agent 的三轮连环问(含答案详解)
java·jvm·spring boot·redis·spring cloud·kafka·mybatis
Mr_pyx2 天前
面试题记录
jvm·数据结构·算法·spring·mybatis