MyBatis数组与集合判断空

目录

集合判空

集合判空2

数组判空

数据判空2


集合判空

此处collection为mapper定义的list名,  不是数据类型

<if test="list!=null and list.size()>0">
	<foreach collection="list" index="index" item="item" open="(" separator="," close=")">
        #{item}
    </foreach>
</if>

集合判空2

在 MyBatis 中,使用 foreach 标签进行遍历集合元素时,可以在其外部添加 <if> 来判断集合是否为空,示例代码如下:

<select id="queryUserByIds" resultType="User">
   select * from user where id in
   <foreach item="id" collection="ids" open="(" separator="," close=")">
      #{id}
   </foreach>
   <if test="ids == null or ids.isEmpty()">
      <bind name="ids" value="'-1'" />
   </if>
</select>

在上述代码中,<if> 标签中的 test 属性判断了集合 ids 是否为 null 或者空集合。如果集合 ids 为空,则使用 bind 标签初始化 ids,这里设置为 -1。在使用 foreach 标签遍历集合时,如果 ids 为 null 或空,则不会进入 foreach 循环。

可以通过在 foreach 标签外部使用 if 标签对集合是否为空进行判断,然后根据情况进行后续操作。

数组判空

此处collection为mapper定义的Array名,  不是数据类型

<if test="arr!=null and arr.length>0">
	 <foreach collection="array" index="index" item="item" open="(" separator="," close=")">
        #{item}
    </foreach>
</if>

数据判空2

在 MyBatis 中也可以用 OGNL 表达式判断数组是否为空。可以使用以下方式来实现:

<select id="findUsersByIds" resultMap="user">
    SELECT *
    FROM user
    WHERE user_id IN
    <foreach item="id" collection="ids" separator="," open="(" close=")">
        #{id}
    </foreach>
    <if test="ids != null and ids.length > 0">
        AND status=1
    </if>
</select>

在上述例子中,ids 就是我们要判断是否为空的数组,if 标签中则使用了 OGNL 表达式进行了判断。

有用请点赞,养成良好习惯!

鼓励、交流、疑问请留言!

猜你喜欢

转载自blog.csdn.net/libusi001/article/details/131524079