MyBatis foreach标签详解

414 阅读2分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第8天,点击查看活动详情

大家都知道用Mybatis等动态语句来处理一些简单的查询操作。比如if where tri等动态SQL,也有一些SQL语句中含有 in 条件,需要迭代条件集合来生成的情况,可以使用mybatis中的 foreach 来实现 SQL 条件的迭代。

Mybatis foreach 标签主要用于循环语句,支持了数据和 set、 List接口的集合,语法格式如下。

  <foreach item="item" index="index" collection="list|array|map key" open="(" separator="," close=")">
具体 参数值
 </foreach>

foreach 标签主要属性:

  • item:表示集合中每一个元素进行迭代时的别名。
    • open:表示该语句以什么开始
  • index:指定一个名字,表示在迭代过程中每次迭代到的位置。
  • separator:表示在每次进行迭代之间以什么符号作为分隔符符)。
  • close:表示该语句以什么结束

测试SQL:

|  1 | Google         | https://www.google.com/    |  23 | US      | 2022-03-10 10:34:34 |
|  2 | GitHub         | https://github.com/        |  13 | US      | 2022-03-10 10:34:34 |
|  3 | Stack Overflow | https://stackoverflow.com/ |  16 | US      | 2022-03-10 10:34:34 |
|  4 | Yandex         | http://www.yandex.ru/      |  11 | RU      | 2022-03-10 10:34:34 

WebsiteMapper.xml 。

<select id="selectWebsite"
    parameterType="com.Website"
    resultType="com.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);

主要Java代码:

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);
        }
    }
}

测试结果控制台打印: Website[id=1,name=GitHub,url=github.com/,age=10,cou…

拓展知识

foreach 遍历数组时是依据元素添加的先后顺序来进行的。如果想按照索引大小遍历,应该使用 for() 循环遍历。list() 和 each() 结合来遍历数组,但测试发现效率不如 foreach() 。

还有在使用foreach时,应提前预估一下collection对象长度。大量数据 in语句会影响性能。