MyBatis处理空值的方法是什么

MyBatis处理空值的方法有两种:

使用if标签:在SQL语句中使用if标签来判断参数是否为空,如果为空则不添加该条件。

<select id="getUserById" parameterType="java.lang.Integer" resultType="User">
    SELECT * FROM user
    WHERE id = #{id}
    <if test="name != null">
        AND name = #{name}
    </if>
</select>

使用where标签:在SQL语句中使用where标签来包裹所有条件,MyBatis会自动去掉第一个条件前的"AND"或"OR"。

<select id="getUserById" parameterType="java.lang.Integer" resultType="User">
    SELECT * FROM user
    <where>
        id = #{id}
        <if test="name != null">
            AND name = #{name}
        </if>
    </where>
</select>

这两种方法都可以有效地处理参数为空时不添加条件,避免出现SQL语法错误。

阅读剩余
THE END