mybatis使用foreach

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时要用$而不是#

相关文章

学习编程是顺着互联网的发展潮流,是一件好事。新手如何学习...
IT行业是什么工作做什么?IT行业的工作有:产品策划类、页面...
女生学Java好就业吗?女生适合学Java编程吗?目前有不少女生...
Can’t connect to local MySQL server through socket \'/v...
oracle基本命令 一、登录操作 1.管理员登录 # 管理员登录 ...
一、背景 因为项目中需要通北京网络,所以需要连vpn,但是服...