美文网首页
动态sql-foreach(mybatis)

动态sql-foreach(mybatis)

作者: 任未然 | 来源:发表于2019-09-29 20:08 被阅读0次

    一、概要

    动态 SQL 的另外一个常用的操作需求是对一个集合进行遍历

    foreach可以遍历三种类型,List,array,Map

    二、属性

    属性 说明
    item 必选。循环体中的具体对象。 在list和数组中是其中的对象,在map中是value。
    collection 必选
    1. 如果传入的是单参数且参数类型是一个List的时候,collection属性值为list
    2. 如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array
    3. 如果传入的参数是多个的时候,我们就需要把它们封装成一个Map了,当然单参数也可以封装成map
    separator 可选。元素之间的分隔符
    open 可选。循环前添加前缀
    close 可选。循环后添加后缀
    index 可选。在list和数组中,index是元素的索引,在map中,index是元素的key

    三、栗子

    遍历集合

    List<User> findByIdList(@Param("ids") List<Integer> ids);
    
    <select id="findByIdList" resultMap="BaseResultMap">
      SELECT
      <include refid="Base_Column_List" />
      from user
      WHERE uid IN
      <foreach collection="ids" item="id" index="index"
               open="(" close=")" separator=",">
        #{id}
      </foreach>
    </select>
    

    遍历map

    // 参数封装成Map的类型
    User findKeysCol(@Param("map")Map<String, Object> map);
    
      <select id="findKeysCol" resultType="User">
            SELECT *
            FROM user
            WHERE
            <foreach item="item" index="key" collection="map"
                     open="" separator="AND" close="">${key} = #{item}
            </foreach>
        </select>
    

    相关文章

      网友评论

          本文标题:动态sql-foreach(mybatis)

          本文链接:https://www.haomeiwen.com/subject/prmxyctx.html