Spring Boot + MyBatis 动态字段更新方法

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

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

  1. 定义实体类

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

  2. Mapper接口

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

    java

    复制代码
    void updateUserSelective(User user);
  3. XML映射文件

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

    xml

    复制代码
    <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)

  1. Service层过滤字段

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

    java

    复制代码
    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);
    }
  2. Mapper接口

    使用Map接收动态字段:

    java

    复制代码
    void updateUserSelective(@Param("id") Long id, @Param("updates") Map<String, Object> updates);
  3. XML映射文件

    动态生成更新语句:

    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(灵活且安全)

  1. 定义SQL提供类

    动态构建安全SQL:

    java

    复制代码
    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();
        }
    }
  2. Mapper接口

    使用@UpdateProvider注解:

    java

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

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


总结

  • 方法一 适合简单场景,字段无需设置为null。

  • 方法二灵活,需严格过滤字段。

  • 方法三推荐用于生产环境,安全且维护性强。

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

相关推荐
陈如水19 分钟前
Spring AI Alibaba 在多 Agent 场景下的实践
java·人工智能·spring
杨运交33 分钟前
091-功能模块-API Key 管理功能模块解析:feature-sa-token 架构设计与数据库持久化
spring boot
行百里er44 分钟前
【Spring Insight 技术分享】如何给 AI 接口调用做滑动窗口限流
spring boot·后端·spring cloud
有个傻瓜1 小时前
一次「查到别家门店订单」的线上事故:Spring Boot 3 + MyBatis-Plus 多租户隔离踩坑复盘
spring boot·mybatis-plus·多租户·ruoyi-vue-plus·线上故障复盘
吃我一窝jio1 小时前
Docker+Jenkins+K8s全流程部署
java·开发语言·笔记·python
Resean02234 小时前
Spring 源码分析(六)循环依赖与三级缓存
java·spring·缓存
在爪洼山玩泥巴4 小时前
fastjson2 JSONPath 取不存在路径,为什么会抛 “not support”?
java·开发语言·jsonpath·fastjson
星落梦生14 小时前
SpringAOP基础笔记(7)
java·开发语言
金銀銅鐵15 小时前
带您看懂字节码指令(四):一条指令里有什么
java·jvm
最强小杰15 小时前
某 OpenAI 兼容网关上的 `kimi-k3.1-pro`:Cline、Zed 接入与 SSE 排错示例
java·服务器·网络·ai