MyBatis foreach标签遍历数组查询

本案例通过商品的搜索案例来解读Mybatis foreach标签遍历数组的方法,背景是购物网站的前台商品按关键字和分类id搜索功能,废话不多数进入今天主角MyBatis foreach标签遍历数组:

ProductMapper

//根据关键字或者分类id集合来收搜索商品
List<Product> selectProductByNameAndCategoryIds(@Param("productName") String productName, @Param("categoryIdList")List<Integer> categoryIdList);

ProductMapper.xml

<sql id="Base_Column_List">
    id, category_id, name, subtitle, main_image, sub_images, detail, price, stock, status, 
    create_time, update_time
</sql>

<!--产品搜索及动态排序List-->
    <select id="selectProductByNameAndCategoryIds" parameterType="map" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List"/>
        from tb_product
        where status = 1
        <if test="productName != null">
            and name like #{productName}
        </if>
        <if test="categoryIdList != null">
            and category_id in
            <foreach item="item" index="index" open="(" separator="," close=")" collection="categoryIdList">
                #{item}
            </foreach>
        </if>
    </select>

foreach的相关属性

属性描述
item循环体中的具体对象,该参数的必填的,item的名字可以自定义的,item=“item”的item对应#{item},也可以是item=“categoryItem” 对应#{categoryItem},通过item的元素去遍历collection集合
separator

元素之间的分隔符,例如在in()的时候,separator=","会自动在元素中间用“,“隔开,避免手动输入逗号导致sql错误,如in(1,2,)这样。该参数可选。

collection要做foreach的对象,作为入参时,上述传入参数为@Param("categoryIdList")List<Integer> categoryIdList,对应collection为categoryIdLists,List<?>对象默认用list代替作为键,数组对象有array代替作为键,Map对象用map代替作为键。上面只是举例,具体collection等于什么,就看你想对那个元素做循环。该参数为必选参数。
openforeach代码的开始符号,一般是(和close=")"合用。常用在in(),values()时。该参数可选。
closeforeach代码的关闭符号,一般是)和open="("合用。常用在in(),values()时。该参数可选。
index

在list和数组中,index是元素的序号,在map中,index是元素的key,该参数可选。

 

 

 

 

 

 

 

 

 

 

最后的sql为:

select  id, category_id, name, subtitle, main_image, sub_images, detail, price, stock, status, create_time, update_time from tb_product where status = 1 and name like #{productName} and category_id in (category_id1,category_id2,category_id3...)


版权声明:本文为weixin_40936211原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。