更新時,把某些字段的值更新為null,但是目前mybatis-plus的update/updateById會忽略實體類中為null的字段,導(dǎo)致這些字段沒有更新還是原來的值。
網(wǎng)上比較常用的有兩種:
1、在實體類的屬性上增加注解:@TableField(updateStrategy = FieldStrategy.IGNORED)
/**
* 手機(jī)號
**/
@TableField(updateStrategy = FieldStrategy.IGNORED)
private String phone;
缺點:當(dāng)在其它接口更新別的字段時,本來沒有想更新這個字段,但是也會把這個字段更新為null。
2、使用LambdaUpdateWrapper的set更新
// set更新
LambdaUpdateWrapper<UserEntity> updateWrapper = Wrappers.lambdaUpdate();
updateWrapper.set(UserEntity::getPhone, null);
updateWrapper.eq(UserEntity::getUserId, "0001");
userMapper.update(null, updateWrapper);
缺點:需要一個一個屬性set,比較麻煩。我平常使用的都是從DTO直接copy到Entity里面,要是updateWrapper.set的話比較繁瑣,而且有的值為null時不更新。
優(yōu)化:
還是使用LambdaUpdateWrapper的set更新,方法update(entity, updateWrapper)當(dāng)?shù)谝粋€參數(shù)實體類entity不為null時,其中entity中為null的屬性不會更新,不為null的會更新, updateWrapper.set()是不論是否為null都更新。
既可以攜程:
LambdaUpdateWrapper<UserEntity> updateWrapper = Wrappers.lambdaUpdate();
if (StringUtils.isEmpty(phone)) {
// 這個值為null,才set,不然sql里面會兩次賦值,執(zhí)行sql時報錯
updateWrapper.set(UserEntity::getPhone, null);
}
updateWrapper.eq(UserEntity::getUserId, "0001");
UserEntity entity = new UserEntity();
entity.setName("張三");
entity.setAge(null);
userMapper.update(null, updateWrapper);
說明:根據(jù)userId更新,name為張三,phone為null,而age不更新。
SQL:文章來源:http://www.zghlxwxcb.cn/news/detail-461151.html
update user set name = '張三', phone = null where user_id = '0001'
結(jié)論:使用update(entity, updateWrapper)更新
屬性為null不更新,使用entity保存;若屬性為null時更新表中字段為null,則用updateWrapper.set()保存數(shù)據(jù),set前需要判斷這個屬性的值為null。文章來源地址http://www.zghlxwxcb.cn/news/detail-461151.html
到了這里,關(guān)于Mybatis-plus更新字段為null的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!