Mybatis-Plus sets field to null
Project scenario:
Recently, when making a requirement, it is necessary to set a certain field in the database to empty
Problem Description:
In the code, set a field to null through the set method, and found that it did not work
Cause Analysis:
After querying, it is because of the default update strategy setting of Mybatis-Plus. There are three strategies for FieldStrategy in Mybatis-Plus:
- IGNORED : Ignored. Regardless of whether the attribute is set or not, all fields will be set in the insert statement, and if the value is not set, it will be updated to null;
- NOT_NULL : Not NULL, the default strategy. That is, null fields are ignored, and "" are not ignored;
- NOT_EMPTY : not empty. If it is null, it is ignored if it is an empty string, that is, if the set value is null, "", it will not be inserted into the database;
The default is NOT_NULL
, that is, null fields are ignored, so the update is unsuccessful.
solution:
The FieldStrategy strategy needs to be adjusted in the following three ways:
Method 1: Adjust the global authentication strategy as follows:
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
Method 2: [ Recommended ] Adjust field validation annotations
For Mybatis-Plus version 3.1.2 and above, according to the specific situation, adjust the validation annotation in the field that needs to be updated, such as verifying that it is not empty:
@TableField(insertStrategy = FieldStrategy.IGNORED, updateStrategy = FieldStrategy.IGNORED)
private String name;
或者单个的例子:
@TableField(updateStrategy = FieldStrategy.IGNORED)
private String username;
Method 3: Use UpdateWrapper (3.x)
Use the following methods for update or insert operations:
//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)
);