在MyBatis中處理空值有幾種方法,具體取決于你想要實現的功能和業務邏輯:
<select id="selectUsers" parameterType="java.util.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>
<select id="selectUsers" parameterType="java.util.Map" resultType="User">
SELECT * FROM users
<where>
<choose>
<when test="username != null">
AND username = #{username}
</when>
<when test="age != null">
AND age = #{age}
</when>
</choose>
</where>
</select>
<sql id="condition">
<if test="username != null">
AND username = #{username}
</if>
<if test="age != null">
AND age = #{age}
</if>
</sql>
<select id="selectUsers" parameterType="java.util.Map" resultType="User">
SELECT * FROM users
<where>
<include refid="condition" />
</where>
</select>
通過以上方式,可以根據需要選擇合適的方法來處理空值,使SQL語句更加靈活和可讀。