阅读量:0
在MyBatis中,可以使用<if>
标签来判断一个List是否为空或null。
示例代码如下:
<select id="selectUsers" resultType="User"> SELECT * FROM users WHERE id IN <foreach item="item" collection="ids" open="(" separator="," close=")"> #{item} </foreach> <if test="ids == null or ids.isEmpty()"> AND 1=0 </if> </select>
在上面的代码中,使用了<if>
标签来判断ids
是否为null或空。如果是,则会在SQL中添加AND 1=0
这个条件,以保证查询结果为空。
另外,如果你是在Java代码中判断List是否为空或null,也可以在传递参数之前进行判断,然后再传递给MyBatis的SQL语句。
示例代码如下:
public List<User> selectUsers(List<Integer> ids) { if (ids == null || ids.isEmpty()) { return Collections.emptyList(); } // 调用MyBatis的SQL语句查询 }
在上面的代码中,先判断ids
是否为null或空,如果是,则直接返回一个空的List,避免调用MyBatis的SQL语句。