Search code examples
mysqlif-statementmybatisibatis

How could I use update statement using <if> statement on MyBatis


I want to know how to use if statement like below case

<update id="update"
    parameterType="com.MyClass">
    UPDATE
        Board SET Status = 1
    <where>
        <if test="A != null and A.length() > 0">AND A = ${A}</if>
    </where>
</update>

This statement works when A!=null and A.length() > 0.

But if A==null, then update whole rows set 1 cause there is no where conditions.

Is there any way to update if there is proper condition, otherwise skip or ignore?

thanks


Solution

  • <update id="update"
        parameterType="com.MyClass">
        UPDATE
            Board SET Status = 1
        <where>
            <choose>
                <when test="A != null and A.length() > 0">
                     AND A = ${A}
                </when>
                <otherwise>
                     AND 0 = 1
                </otherwise>
            </choose>
        </where>
    </update>
    

    With condition 0 = 1 the where fails and no updates are done