How is the if-else usage in MyBatis?
In MyBatis, you can use the
The sample code is shown below:
<select id="selectUsers" parameterType="map" resultType="User">
SELECT * FROM users
<where>
<if test="username != null">
AND username = #{username}
</if>
<if test="age != null">
AND age = #{age}
</if>
</where>
</select>
In the given example, two conditional statements, “AND username = #{username}” and “AND age = #{age}”, were dynamically added based on the conditions.
If both the username and age are not empty, the SQL statement will look something like this:
SELECT * FROM users
WHERE username = ? AND age = ?
If the username is empty and the age is not empty, the SQL statement will look something like this:
SELECT * FROM users
WHERE age = ?
If the username is not empty and the age is empty, the SQL statement will be something like this:
SELECT * FROM users
WHERE username = ?
Using the