How does MyBatis determine if a list is empty or null?
In MyBatis, you can use the
The example code is as follows:
<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>
In the code above, the
Additionally, if you need to check if a List is empty or null in Java code, you can also do the check before passing the parameter to the SQL statement in MyBatis.
The sample code is as follows:
public List<User> selectUsers(List<Integer> ids) {
if (ids == null || ids.isEmpty()) {
return Collections.emptyList();
}
// 调用MyBatis的SQL语句查询
}
In the above code, first check if ids is null or empty, if it is, simply return an empty List to avoid calling MyBatis SQL statements.