MyBatis `if` Tag Usage Guide
In MyBatis, you can use the if tag to dynamically concatenate SQL statements. Depending on the condition, the if tag can determine whether to include a certain segment of SQL statement. If the condition is met, the SQL statement will be executed; otherwise, it will be ignored.
For example, in the Mapper XML file, the if tag can be used as follows:
<select id="getUserById" parameterType="int" resultType="User">
SELECT * FROM user
<where>
<if test="id != null">
AND id = #{id}
</if>
<if test="name != null">
AND name = #{name}
</if>
</where>
</select>
In the example above, if the parameter “id” is not empty, the SQL statement will be appended with “AND id = #{id}”; if “name” is not empty, “AND name = #{name}” will be appended to the SQL statement. This allows for dynamically constructing SQL queries based on the input parameters, enabling flexible SQL search operations.