简介
foreach 标签用于循环语句,它很好的支持了数据和 List、set 接口的集合,并对此提供遍历的功能。
对于一些 SQL 语句中含有 in 条件,需要迭代条件集合来生成的情况,可以使用 foreach 来实现 SQL 条件的迭代。
select *
from TABLE
where (id=1 or id=3 or id=4)
要查询一个表中id为1,3,4的数据,可以把需要查的这些id的数据存放到一个集合中,通过遍历这个集合来查询到这些数据,这种时候我们就用到foreach了。
foreach 标签有六个属性:item,index,collection,open, close,separator
属性 | 作用 |
---|---|
item | 表示集合中每一个元素进行迭代时的别名 |
index | 指定一个名字,表示在迭代过程中每次迭代到的位置 |
open | 表示该语句以什么开始(既然是 in 条件语句,所以必然以’('开始) |
close | 表示该语句以什么结束(既然是 in 条件语句,所以必然以’)'结束。 |
separator | 表示在每次进行迭代之间以什么符号作为分隔符(既然是 in 条件语句,所以必然以‘,’作为分隔符)。 |
collection | 该属性是必选的,但在不同情况下该属性的值是不一样的,主要有以下 3 种情况: (1)如果传入的是单参数且参数类型是一个 List,collection 属性值为 list (2)如果传入的是单参数且参数类型是一个 array 数组,collection 的属性值为 array (3)如果传入的参数是多个,需要把它们封装成一个 Map,当然单参数也可以封装成 Map。Map 的 key 是参数名,collection 属性值是传入的 List 或 array 对象在自己封装的 Map 中的 key。 |
语法格式
trim 一般用于去除 SQL 语句中多余的 AND 关键字、逗号,或者给 SQL 语句前拼接 where、set 等后缀,可用于选择性插入、更新、删除或者条件查询等操作。trim 语法格式如下。
<foreach item="item" index="index" collection="list|array|map key" open="(" separator="," close=")">
参数值
</foreach>
网络案例
+----+----------------+----------------------------+-----+---------+---------------------+
| id | name | url | age | country | createtime |
+----+----------------+----------------------------+-----+---------+---------------------+
| 1 | 编程帮 | https://www.biancheng.net/ | 10 | CN | 2021-02-23 10:20:40 |
| 2 | C语言中文网 | http://c.biancheng.net/ | 12 | CN | 2021-03-08 11:23:27 |
| 3 | 百度 | https://www.baidu.com/ | 18 | CN | 2021-03-08 11:23:53 |
| 4 | 淘宝 | https://www.taobao.com/ | 17 | CN | 2021-03-10 10:33:54 |
| 5 | Google | https://www.google.com/ | 23 | US | 2021-03-10 10:34:34 |
| 6 | GitHub | https://github.com/ | 13 | US | 2021-03-10 10:34:34 |
| 7 | Stack Overflow | https://stackoverflow.com/ | 16 | US | 2021-03-10 10:34:34 |
| 8 | Yandex | http://www.yandex.ru/ | 11 | RU | 2021-03-10 10:34:34 |
+----+----------------+----------------------------+-----+---------+---------------------+
<select id="selectWebsite"
parameterType="net.biancheng.po.Website"
resultType="net.biancheng.po.Website">
SELECT id,name,url,age,country
FROM website WHERE age in
<foreach item="age" index="index" collection="list" open="("
separator="," close=")">
#{age}
</foreach>
</select>
基础环境
1.数据库准备
# 创建一个名称为t_customer的表
CREATE TABLE t_customer (
id int(32) PRIMARY KEY AUTO_INCREMENT,
username varchar(50),
jobs varchar(50),
phone varchar(16)
);
# 插入3条数据
INSERT INTO t_customer VALUES ('1', 'joy', 'teacher', '13733333333');
INSERT INTO t_customer VALUES ('2', 'jack', 'teacher', '13522222222');
INSERT INTO t_customer VALUES ('3', 'tom', 'worker', '15111111111');
2.新建项目或Module
3 pom.xml中添加
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent