mybatis怎么判断list为空或null

avatar
作者
筋斗云
阅读量: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语句。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!