mybatis使用foreach

本文详细介绍了Java中foreach的常见应用场景,包括list、array和map的不同使用方式,以及如何通过@Param注解自定义collection属性。重点讲解了item、index、separator等参数的作用和示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

foreach常用属性:

collection:

需做foreach的对象,作为入参时,list、array对象时,collection属性值分别默认用"list"、"array"代替,Map对象没有默认的属性值。但是,在作为入参时可以使用@Param(“paramName”)注解来设置自定义collection属性值,设置keyName后,list、array会失效;

item: 集合元素迭代时的别名称,该参数为必选项

index:map中代指key,其它时用于表示在迭代过程中,每次迭代到的位置

separator:元素间的分隔符

open:遍历集合开始时使用

close:遍历集合结束时使用

使用场景:

1、collection为list时:

<resultMap id="BaseResultMap" type="com.list.demo">
        <result column="id" property="id"/>
        <result column="name" property="name"/>
        <result column="age" property="age"/>
        <result column="gender" property="gender"/>
        <result column="address" property="address"/>
    </resultMap>

<select id="selectTestList1" resultMap="BaseResultMap">
    SELECT id, name, age, gender, address
    FROM test_01
    WHERE
    id in
    <foreach collection="ids" item="id" separator="," open="(" close=")">
        #{id}
    </foreach>
</select>

对应的Mapper接口为:List<TestList> selectTestList1(@Param("ids")List<Integer> ids);

2、collection为array时:

<select id="selectTestList2" resultMap="BaseResultMap">
    SELECT id, name, age, gender, address
    FROM test_01
    WHERE
    name in
    <foreach collection="names" item="name" separator="," open="(" close=")">
        #{name}
    </foreach>
</select>

对应的Mapper接口为:List<TestList> selectTestList2(@Param("names")String[] names);

3、collection为map时:

<select id="selectTestList3" resultMap="BaseResultMap">
    SELECT id, name, age, gender, address
    FROM test_01
    WHERE
    (name, age) in
    <foreach collection="maps" item="v" index="k" separator="," open="(" close=")">
        (#{k}, #{v})
    </foreach>
</select>

对应的Mapper接口为:List<TestList> selectTestList3(@Param("maps")Map<String, Integer> maps);

特别注意:当collection为list或array时,index代表的是当前序号

比如:

    <foreach collection="list" item="item" index="i">
        <if test="i > 0">
            ${item[i-1]}=#{item}
        </if>
    </foreach>

注意:用index时要用$而不是#

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值