sql语句 update字段null不能用is null
update字段为 null 值时,
要用
1
|
set column = null , |
而不是
1
|
set column is null |
X UPDATE tableA set 字段a is null WHERE字段b = 条件;
例:
1
2
|
mysql> UPDATE t SET col3 is null WHERE col1 = 'a' ; ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'is null WHERE col1 = ' a '' at line 1 |
0 UPDATE tableA set 字段a = null WHERE字段b = 条件;
例:
1
2
|
mysql> UPDATE t SET col3 = null WHERE col1 = 'a' ; Query OK, 1 row affected (0.03 sec) |
update更新数据时null字段是否更新进数据库总结
情况一:不需要更新进数据库
方法1:直接用sql语句方式,需要更新哪个字段就set xxclounm 即可
方法2:使用mybatis带的方法 updateById(Entry entry),传入entry对象只设置需要更新字段即可。
解析:mybatis-plus在update时对null字段有三种处理策略分别是:
-
IGNORED
:0 忽略 -
NOT_NULL
:1 非 NULL,默认策略 -
NOT_EMPTY
:2 非空
默认策略是忽略null字段,所以只需要将entry中不需要更新的字段不做处理即可。注意:如果entry中字段设置为空字符串" " 则会更新进数据库
方法3:使用updateWapper,其实和方法2原理一样 如下例子只更新age字段 ,同样受更新策略影响:
1
2
3
4
5
|
UpdateWrapper< User > updateWrapper = new UpdateWrapper<>(); updateWrapper.eq( "name" , "rhb" ); User user = new User (); user .setAge(18); userMapper. update ( user , updateWrapper); |
情况二:需要更新进数据库 (推荐方法3)
方法1:直接用sql语句方式,需要更新哪个字段就set xxclounm 即可
方法2:使用mybatis带的方法 updateById(Entry entry),传入entry对象只设置需要更新字段即可。另外在entry类中需要更新null的字段上加上注解updateStrategy 如下面例子:
1
2
3
4
5
|
/** * 单位 */ @TableField (value = "UNIT" , updateStrategy = FieldStrategy.IGNORED) private String unit; |
或者设置全局更新策略(按需要设置单个字段或者全局)
1
2
3
4
5
|
# yml配置 mybatis-plus: global-config : db-config : field-strategy : not_empty |
方法3:使用updateWapper,不受更新策略影响。推荐此方法,设置完策略后别人在不知情情况下可能会在不想设置null时将你设置的字段更新为空
1
2
3
|
LambdaUpdateWrapper< User > lambdaUpdateWrapper = new LambdaUpdateWrapper<>(); lambdaUpdateWrapper.eq( User ::getName, "rhb" ). set ( User ::getAge, null ); Integer rows = userMapper. update ( null , lambdaUpdateWrapper); |
以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/Olivia_Vang/article/details/100290032