Preface
When updating, the values of some fields are updated to null, but the update/updateById of mybatis-plus currently ignores the fields in the entity class that are null, resulting in these fields not being updated or the original value.
There are two common online use:
1. Add annotation to the properties of the entity class: @TableField(updateStrategy = )
/** * Phone number **/ @TableField(updateStrategy = ) private String phone;
Disadvantages: When you update other fields on other interfaces, you did not want to update this field, but you would also update this field to null.
2. Use LambdaUpdateWrapper to update set
// set update LambdaUpdateWrapper<UserEntity> updateWrapper = (); (UserEntity::getPhone, null); (UserEntity::getUserId, "0001"); (null, updateWrapper);
Disadvantages: You need to set one by one attribute, which is more troublesome. I usually use DTO to directly copy it from Entity. If so, it is more cumbersome, and some values are null and do not update.
optimization:
Or use LambdaUpdateWrapper's set update. When the first parameter entity class entity is not null, the attribute null in the entity will not be updated, and those that are not null will be updated. () is updated regardless of whether it is null or not.
You can also use Ctrip:
LambdaUpdateWrapper<UserEntity> updateWrapper = (); if ((phone)) { // This value is null, only set, otherwise the value will be assigned twice in SQL, and an error will be reported when executing SQL (UserEntity::getPhone, null); } (UserEntity::getUserId, "0001"); UserEntity entity = new UserEntity(); ("Zhang San"); (null); (null, updateWrapper);
Note: According to userId update, name is Zhang San, phone is null, and age is not updated.
SQL:
update user set name = 'Zhang San', phone = null where user_id = '0001'
Conclusion: Use update(entity, updateWrapper) to update
If the property is null and not updated, use entity to save; if the field in the update table is null when the property is null, then use () to save the data. Before setting, you need to judge that the value of this property is null.
Summarize
This is the end of this article about the two commonly used methods and optimizations for Mybatis-plus update field as null. For more related contents for Mybatis-plus update field as null, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!