MyBatis-Plus 如何将字段值更新为 NULL
在使用 MyBatis-Plus 进行数据库更新操作时,默认情况下,若实体对象中某字段值为 null,框架会自动跳过该字段的更新,不会生成对应的 SET column = NULL SQL 语句。这导致即使显式设置字段为 null,也无法真正更新到数据库。
若需强制将字段更新为 NULL,必须通过配置字段级别的策略来覆盖默认行为。
解决方案
在目标字段上添加 @TableField 注解,并设置 updateStrategy = FieldStrategy.IGNORED,表示该字段无论值是否为 null 都应参与更新。
数据库表结构(示例)
CREATE TABLE userinfo (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50),
birthday DATE
);
实体类定义(关键修改)
package com.sbmp.bean;
import java.time.LocalDate;
import com.baomidou.mybatisplus.annotation.FieldStrategy;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;
@Data
public class Userinfo {
/**
* 主键
*/
@TableId(type = IdType.AUTO)
private Integer id;
/**
* 姓名
*/
private String name;
/**
* 生日:需允许更新为 NULL
*/
@TableField(updateStrategy = FieldStrategy.IGNORED)
private LocalDate birthday;
}
Mapper 接口
package com.sbmp.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.sbmp.bean.Userinfo;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface UserinfoMapper extends BaseMapper<Userinfo> {
}
Controller 测试方法
package com.sbmp.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.sbmp.bean.Userinfo;
import com.sbmp.mapper.UserinfoMapper;
@RestController
@RequestMapping("/api")
public class UserinfoController {
@Autowired
private UserinfoMapper userinfoMapper;
@GetMapping("/update-null")
public String updateBirthdayToNull() {
Userinfo user = new Userinfo();
user.setId(1);
user.setName("林黛玉");
user.setBirthday(null); // 显式设为 null
int result = userinfoMapper.updateById(user);
return result > 0 ? "更新成功,生日已置空" : "更新失败";
}
}
执行结果
当调用 /api/update-null 接口后,日志中将输出如下 SQL:
UPDATE userinfo
SET name = '林黛玉', birthday = NULL
WHERE id = 1
此时,birthday 字段成功被更新为 NULL。
补充说明:@TableField 各策略含义
| 策略 | 说明 |
|---|---|
IGNORED |
无论值是否为空,均参与更新(包括设置为 NULL) |
DEFAULT |
仅当字段值不为 null 时才参与更新(默认行为) |
NOT_NULL |
仅当字段值非 null 时才更新 |
NEVER |
永不参与更新 |
⚠️ 注意:
insertStrategy用于控制插入时的行为,whereStrategy用于控制 WHERE 条件中的字段处理方式。
总结
若需让 MyBatis-Plus 正确执行字段置为 NULL 的更新操作,务必对相关字段启用 updateStrategy = FieldStrategy.IGNORED。这是避免"空值被忽略"的最直接有效方式。