zoukankan      html  css  js  c++  java
  • MyBatis:SQL语句中的foreach标签的详细介绍

    foreach 也就是遍历迭代,在SQL中通常用在 in 这个关键词的后面

    foreach元素的属性主要有 item,index,collection,open,separator,close。

    分别代表:

    item表示集合中每一个元素进行迭代时的别名,
    index用于表示在迭代过程中,每次迭代到的位置,
    open表示该语句以什么开始,
    separator表示在每次进行迭代之间以什么符号作为分隔 符,
    close表示以什么结束
     
    代码片段:
    <select id="selectByIds" resultType="com.txw.pojo.User">
            select * from user where id in
            <foreach collection="list" index="index" item="item" open="(" separator="," close=")">
                #{item}
            </foreach>
    </select>
     

    而最为重要的就是collection属性了,既然是迭代就表示传入的参数是多个,这时候传入的参数就有以下几种可能:

    1. 传入的参数为list的时候

     对应的Dao中的Mapper文件是:

    public List<User> selectByIds(List<Integer> ids);
     
    xml文件代码片段:
    <select id="selectByIds" resultType="com.txw.pojo.User">
            select * from user where id in
            <foreach collection="list" index="index" item="item" open="(" separator="," close=")">
                #{item}
            </foreach>
    </select>
     
     
    2. 传入的参数为Array的时候

    对应的Dao中的Mapper文件是:

    public List<User> selectByIds(int[] ids);

    xml文件代码片段: 

    <select id="selectByIds" resultType="com.txw.pojo.User">
            select * from user where id in
            <foreach collection="array" index="index" item="item" open="(" separator="," close=")">
                #{item}
            </foreach>
        </select>
     
    3. 传入的参数为Map的时候
     
    对应的Dao中的Mapper文件是:

    public List<User> selectByIds(Map<String, Object> params);

    xml文件代码片段: 
    <select id="selectByIds" resultType="com.txw.pojo.User">
            select * from user where  id in
            <foreach collection="ids" index="index" item="item" open="(" separator="," close=")">
                #{item}
            </foreach>
        </select>
     
    map的时候需要注意的是:collection的值“ids”是存储在map中的key(比如:map.put("ids",ids));尤其需要注意;
     
  • 相关阅读:
    文件上传的核心点 一(59)
    ajax1—php(27)
    php—Smarty-缓存2(26)
    php—Smarty-缓存1(25)
    java—实现一个监听器HttpServletRequest的创建销毁、在线人数 (56)
    Linux—virtualbox系统安装(1)
    php—Smarty-2
    java—不同的用户登录以后可以看到不同的菜单(后台可以实现对用户菜单的管理) 1 (55)
    java—数据存储过程 (54)
    java—ThreadLocal模式与OSIV模式(53)
  • 原文地址:https://www.cnblogs.com/xuanwei-qingfeng/p/8435181.html
Copyright © 2011-2022 走看看