<foreach item="item" index="index" collection="list|array|map key" open="(" separator="," close=")"> 参数值 </foreach>foreach 标签主要有以下属性,说明如下。
(
开始)。,
作为分隔符)。)
开始)。+----+----------------+----------------------------+-----+---------+---------------------+ | id | name | url | age | country | createtime | +----+----------------+----------------------------+-----+---------+---------------------+ | 1 | 编程帮 | https://www.lmcjl.com/ | 10 | CN | 2021-02-23 10:20:40 | | 2 | C语言中文网 | http://task.lmcjl.com/ | 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 | +----+----------------+----------------------------+-----+---------+---------------------+WebsiteMapper.xml 中代码如下。
<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>WebsiteMapper 类中相应方法如下。
public List<Website> selectWebsite(List<Integer> ageList);测试代码如下。
public class Test { public static void main(String[] args) throws IOException { // 读取配置文件mybatis-config.xml InputStream config = Resources.getResourceAsStream("mybatis-config.xml"); // 根据配置文件构建 SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(config); // 通过SqlSessionFactory创建SqlSession SqlSession ss = ssf.openSession(); List<Integer> ageList = new ArrayList<Integer>(); ageList.add(10); ageList.add(12); List<Website> siteList = ss.selectList("net.biancheng.mapper.WebsiteMapper.selectWebsite", ageList); for (Website ws : siteList) { System.out.println(ws); } } }输出结果如下。
DEBUG [main] - ==> Preparing: SELECT id,name,url,age,country FROM website WHERE age in ( ? , ? )
DEBUG [main] - ==> Parameters: 10(Integer), 12(Integer)
DEBUG [main] - <== Total: 2
Website[id=1,name=编程帮,url=https://www.lmcjl.com/,age=10,country=CN]
Website[id=2,name=C语言中文网,url=http://task.lmcjl.com/,age=12,country=CN]
本文链接:http://task.lmcjl.com/news/18789.html