Mybatis-plus设置某字段为null
需求:
mapper.setxxx=null;
问题:
该行不起作用
原因:
设置某属性值时,mybatis-plus中FieldStrategy 有三种策略:
- IGNORED:忽略。即,不管有没有有设置属性,所有的字段都会设置到insert语句中;如果没设置,值会更新为null;
- NOT_NULL:非 NULL,默认策略。即忽略设置为null的命令,不忽略””;
- NOT_EMPTY:非空。即如果设置值为null或者””,不会插入数据库;
解决方法:
一、调整全局的验证策略 (麻烦)
mybatis-plus:
mapper-locations: classpath:/mapper/**/*.xml
typeAliasesPackage: com.test.application.test.admin.entity
global-config:
#主键类型 0:"数据库ID自增", 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID";
id-type: 0
#字段策略 0:"忽略判断",1:"非 NULL 判断"),2:"非空判断"
field-strategy: 0
#驼峰下划线转换
db-column-underline: true
#刷新mapper 调试神器
refresh-mapper: true
#数据库大写下划线转换
#capital-mode: true
configuration:
map-underscore-to-camel-case: true
cache-enabled: true
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
二、调整字段验证注解 (推荐)
@TableField(insertStrategy = FieldStrategy.IGNORED, updateStrategy = FieldStrategy.IGNORED)
private LocalDateTime completeTime;
三、使用 UpdateWrapper (3.x) (水杉不支持)
//updateAllColumnById(entity) // 全部字段更新: 3.0已经移除
mapper.update(
new User().setName("mp").setAge(3),
Wrappers.<User>lambdaUpdate()
.set(User::getEmail, null) //把email设置成null
.eq(User::getId, 2)
);
// 也可以参考下面这种写法
mapper.update(
null,
Wrappers.<User>lambdaUpdate()
.set(User::getAge, 3)
.set(User::getName, "mp")
.set(User::getEmail, null) // 把email设置成null
.eq(User::getId, 2)
);