在MyBatis中處理數(shù)據(jù)庫(kù)的NULL值有多種方法,可以通過(guò)if、choose、when等標(biāo)簽來(lái)處理。
<select id="getUserById" parameterType="int" resultType="User">
SELECT * FROM user WHERE id = #{id}
<if test="name != null">
AND name = #{name}
</if>
</select>
<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>
<select id="getUserByName" parameterType="String" resultType="User">
SELECT * FROM user WHERE name = '${name}'
</select>
需要注意的是,對(duì)于使用${}占位符的方式,需要注意SQL注入問(wèn)題,建議使用#{name}來(lái)處理參數(shù)。