MyBatis: Check Collection Empty

In MyBatis, you can use the isEmpty() function in the OGNL expression language to check if a collection is empty.

For example, in MyBatis’s select statement, you can check if a collection is empty like this:

<select id="selectUsers" resultMap="userResultMap">
    SELECT * FROM users
    <where>
        <if test="userIds != null and !userIds.isEmpty()">
            AND user_id IN
            <foreach collection="userIds" item="userId" open="(" close=")" separator=",">
                #{userId}
            </foreach>
        </if>
    </where>
</select>

In the example given above, userIDs is a parameter of type List. We use the isEmpty() function to check if it is empty, and if it is not empty, we execute the corresponding SQL statement.

bannerAds