How to handle NULL values in Mybatis?
There are multiple ways to handle NULL values in MyBatis, such as using if, choose, and when tags.
- Handling NULL values using the if tag:
<select id="getUserById" parameterType="int" resultType="User">
SELECT * FROM user WHERE id = #{id}
<if test="name != null">
AND name = #{name}
</if>
</select>
- Handle NULL values using the choose and when tags.
<select id="getUserById" parameterType="int" resultType="User">
SELECT * FROM user WHERE id = #{id}
<choose>
<when test="name != null">
AND name = #{name}
</when>
<otherwise>
AND name IS NULL
</otherwise>
</choose>
</select>
- Handle NULL values using ${} placeholders.
<select id="getUserByName" parameterType="String" resultType="User">
SELECT * FROM user WHERE name = '${name}'
</select>
It is important to note that when using the ${} placeholder method, there is a risk of SQL injection. It is recommended to use #{name} to handle parameters.