MyBatis中动态SQL使用 foreach 遍历集合

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_23179075/article/details/79164539

请注明出处:http://blog.csdn.net/qq_23179075/article/details/79164539

MyBatis中动态SQL使用 foreach 遍历集合

需求 : 根据 type 字段查询表中的数据 type 可以是: 0 , 1 , 2 几个值的所有组合, 也可以为空

MySQL: Mapper.xml

    <select id="getDataByTypes" resultMap="RM">
        SELECT
        <include refid="columns"/>
        FROM
        `idata`
        WHERE
        ... --其它条件
        <if test="@Ognl@isNotEmpty(types)">
            AND `type`IN
            <foreach collection="types" open="(" close=")" separator="," item="type">
                #{type, jdbcType=SMALLINT}
            </foreach>
        </if>
         ... --其它条件
    </select>

Oracle: Mapper.xml

    <select id="getDataByTypes" resultMap="RM">
        SELECT
        <include refid="columns"/>
        FROM
        "IDATA"
        WHERE
        ... --其它条件
        <if test="@Ognl@isNotEmpty(types)">
            AND "TYPE" IN
            <foreach collection="types" open="(" close=")" separator="," item="type">
                #{type, jdbcType=SMALLINT}
            </foreach>
        </if>
        ... --其它条件
    </select>

Dao类

List<DataBean> getDataByTypes(@Param("types")List<Integer> types);
关键字 使用 解释
collection collection=”types” 参数是跟一个集合,这里的 types 就是需要遍历的集合
open open=”(“ foreach 遍历开始拼接的字符串
close close=”)” foreach 遍历结束拼接的字符串
separator separator=”,” 遍历 item 之间的分割符
item item=”type” 遍历后 item 的名字

实际SQL

假设 传入的 types[0,1,2]
上面通过 foreach 遍历后完整的SQL 如下

and type in (0,1,2)

猜你喜欢

转载自blog.csdn.net/qq_23179075/article/details/79164539