MyBatis中怎么處理數(shù)據(jù)庫(kù)的NULL值

小億
171
2024-03-07 14:08:24

在MyBatis中處理數(shù)據(jù)庫(kù)的NULL值有多種方法,可以通過(guò)if、choose、when等標(biāo)簽來(lái)處理。

  1. 使用if標(biāo)簽處理NULL值:
<select id="getUserById" parameterType="int" resultType="User">
    SELECT * FROM user WHERE id = #{id}
    <if test="name != null">
        AND name = #{name}
    </if>
</select>
  1. 使用choose、when標(biāo)簽處理NULL值:
<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>
  1. 使用${}占位符處理NULL值:
<select id="getUserByName" parameterType="String" resultType="User">
    SELECT * FROM user WHERE name = '${name}'
</select>

需要注意的是,對(duì)于使用${}占位符的方式,需要注意SQL注入問(wèn)題,建議使用#{name}來(lái)處理參數(shù)。

0