How to resolve the error with empty list being passed into MyBatis?
In MyBatis, if an empty List is passed, it may result in a java.lang.NullPointerException exception. To address this issue, you can add some defensive programming logic in the code to handle an empty List.
Here is one possible solution:
- Before calling the Mapper method, check if the List is empty. If it is empty, you can just return an empty result.
if (list == null || list.isEmpty()) {
return new ArrayList<>(); // 返回一个空结果
}
- for each
<foreach collection="list" item="item" open="WHERE" separator="," close="">
<if test="list != null and !list.isEmpty()">
column = #{item}
</if>
</foreach>
By using the above method, you can avoid the occurrence of a NullPointerException when the input List is empty, and return an empty result.