MyBatis List 判空:使用 `<if>` 标签和 OGNL 表达式
在 MyBatis 中,可以使用 <if> 标签来判断一个 List 是否为空。以下是一个示例:
<select id="selectUsers" resultType="User">
SELECT * FROM users
<where>
<if test="usernames != null and usernames.size() > 0">
AND username IN
<foreach item="username" collection="usernames" open="(" separator="," close=")">
#{username}
</foreach>
</if>
</where>
</select>
在上述示例中,<if> 标签会首先判断 usernames 是否为空,并且长度大于 0,如果满足条件,则会动态生成一个 IN 语句,以将 usernames 中的值作为参数传递给 SQL 语句。
另外,还可以使用 OGNL 表达式来判断 List 是否为空,示例如下:
<select id="selectUsers" resultType="User">
SELECT * FROM users
<where>
<if test="usernames != null and !usernames.isEmpty()">
AND username IN
<foreach item="username" collection="usernames" open="(" separator="," close=")">
#{username}
</foreach>
</if>
</where>
</select>
在这个示例中,<if> 标签的判断条件使用了 !usernames.isEmpty() 来判断 List 是否为空。
原文地址: https://www.cveoy.top/t/topic/b9vy 著作权归作者所有。请勿转载和采集!