java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringBoot MyBatis字段更新

SpringBoot+MyBatis实现动态字段更新的三种方法

作者:BillKu

字段更新是指在数据库表中修改特定列的值的操作,这种操作可以通过多种方式进行,具体取决于业务需求和技术环境,本文给大家介绍了在Spring Boot和MyBatis中,实现动态更新不固定字段的三种方法,需要的朋友可以参考下

在Spring Boot和MyBatis中,实现动态更新不固定字段的步骤如下:

方法一:使用MyBatis动态SQL(适合字段允许为null的场景)

定义实体类

包含所有可能被更新的字段。

Mapper接口

定义更新方法,参数为实体对象:

void updateUserSelective(User user);

XML映射文件

使用<set><if>动态生成SQL:

<update id="updateUserSelective" 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>

注意:此方法无法将字段更新为null,因为参数为null时条件不成立。

方法二:使用Map和字段过滤(支持字段更新为null)

Service层过滤字段

在Service中定义允许更新的字段,并过滤请求参数:

public void updateUser(Long id, Map<String, Object> updates) {
    Set<String> allowedFields = Set.of("name", "age", "address", "phone");
    updates.keySet().retainAll(allowedFields); // 过滤非法字段
    userMapper.updateUserSelective(id, updates);
}

Mapper接口

使用Map接收动态字段:

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

XML映射文件

动态生成更新语句:

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

注意:使用${key}存在SQL注入风险,需在Service层严格过滤字段名。

方法三:使用@UpdateProvider(灵活且安全)

定义SQL提供类

动态构建安全SQL:

public class UserSqlProvider {
    public String updateSelective(Map<String, Object> params) {
        Long id = (Long) params.get("id");
        Map<String, Object> updates = (Map<String, Object>) params.get("updates");
        Set<String> allowedFields = Set.of("name", "age", "address", "phone");
        
        StringBuilder sql = new StringBuilder("UPDATE user SET ");
        allowedFields.forEach(field -> {
            if (updates.containsKey(field)) {
                sql.append(field).append(" = #{updates.").append(field).append("}, ");
            }
        });
        sql.setLength(sql.length() - 2); // 移除末尾逗号
        sql.append(" WHERE id = #{id}");
        return sql.toString();
    }
}

Mapper接口

使用@UpdateProvider注解:

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

优点:避免SQL注入,动态生成安全语句。

总结

根据需求选择合适方案,确保字段更新的灵活性和安全性。

到此这篇关于SpringBoot+MyBatis实现动态字段更新的三种方法的文章就介绍到这了,更多相关SpringBoot MyBatis字段更新内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文