SoFunction
Updated on 2025-04-25

Three ways to implement dynamic field updates in SpringBoot+MyBatis

In Spring Boot and MyBatis, the steps to dynamically update unfixed fields are as follows:

Method 1: Use MyBatis dynamic SQL (suitable for scenarios where fields are allowed to be null)

Define entity classes

Contains all fields that may be updated.

Mapper interface

Define the update method, the parameters are entity objects:

void updateUserSelective(User user);

XML map file

use<set>and<if>Dynamically generate SQL:

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

Notice: This method cannot update the field tonullbecause the parameters arenullThe conditions are not true.

Method 2: Use Map and field filtering (support fields to update to null)

Service layer filter field

Define fields that allow updates in Service and filter request parameters:

public void updateUser(Long id, Map&lt;String, Object&gt; updates) {
    Set&lt;String&gt; allowedFields = ("name", "age", "address", "phone");
    ().retainAll(allowedFields); // Filter illegal fields    (id, updates);
}

Mapper interface

Use Map to receive dynamic fields:

void updateUserSelective(@Param("id") Long id, @Param("updates") Map<String, Object> updates);

XML map file

Dynamically generate update statements:

<update >
    UPDATE user
    <set>
        <foreach collection="updates" index="key" item="value" separator=",">
            ${key} = #{value}
        </foreach>
    </set>
    WHERE id = #{id}
</update>

Notice:use${key}There is a risk of SQL injection, and field names need to be strictly filtered at the Service layer.

Method 3: Use @UpdateProvider (flexible and safe)

Define SQL-provided classes

Dynamically build secure SQL:

public class UserSqlProvider {
    public String updateSelective(Map&lt;String, Object&gt; params) {
        Long id = (Long) ("id");
        Map&lt;String, Object&gt; updates = (Map&lt;String, Object&gt;) ("updates");
        Set&lt;String&gt; allowedFields = ("name", "age", "address", "phone");
        
        StringBuilder sql = new StringBuilder("UPDATE user SET ");
        (field -&gt; {
            if ((field)) {
                (field).append(" = #{updates.").append(field).append("}, ");
            }
        });
        (() - 2); // Remove the end comma        (" WHERE id = #{id}");
        return ();
    }
}

Mapper interface

Use @UpdateProvider annotation:

@UpdateProvider(type = , method = "updateSelective")
void updateUserSelective(@Param("id") Long id, @Param("updates") Map<String, Object> updates);

advantage: Avoid SQL injection and generate safe statements dynamically.

Summarize

  • Method 1Suitable for simple scenarios, fields do not need to be set tonull

  • Method 2Flexible and requires strict filtering of fields.

  • Method 3Recommended for use in production environments, safe and maintainable.

Select the right plan according to your needs to ensure the flexibility and security of field updates.

This is the end of this article about SpringBoot+MyBatis’s three methods to implement dynamic field updates. For more related SpringBoot MyBatis field update content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!