MyBatis foreach标签<foreach></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...)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值