MyBatis Set Tag: Dynamic SQL Updates

In MyBatis, the set tag is used to specify the fields to be updated in an update statement along with their corresponding values. The subtags contained within the set tag will generate a set of comma-separated assignment statements used to update the values of fields in a database record.

For example, consider the following update statement:

<update id="updateUser" parameterType="User">
  UPDATE users
  <set>
    <if test="name != null">
      name = #{name},
    </if>
    <if test="age != null">
      age = #{age},
    </if>
  </set>
  WHERE id = #{id}
</update>

In the example above, the ‘set’ tag contains two ‘if’ conditional subtags that check if the ‘name’ and ‘age’ fields are empty. If not empty, it will generate corresponding assignment statements. The final update statement is as follows:

UPDATE users
SET
  name = #{name},
  age = #{age}
WHERE id = #{id}

We can use the set tag to dynamically generate update statements based on the input parameters, allowing for flexible update operations.

bannerAds