当前位置: 代码网 > it编程>编程语言>Java > Mybatis-plus更新字段为null两种常用方法及优化

Mybatis-plus更新字段为null两种常用方法及优化

2024年05月18日 Java 我要评论
前言更新时,把某些字段的值更新为null,但是目前mybatis-plus的update/updatebyid会忽略实体类中为null的字段,导致这些字段没有更新还是原来的值。网上比较常用的有两种:1

前言

更新时,把某些字段的值更新为null,但是目前mybatis-plus的update/updatebyid会忽略实体类中为null的字段,导致这些字段没有更新还是原来的值。

网上比较常用的有两种:

1、在实体类的属性上增加注解:@tablefield(updatestrategy = fieldstrategy.ignored)

    /**
     * 手机号
     **/
    @tablefield(updatestrategy = fieldstrategy.ignored)
    private string phone;

缺点:当在其它接口更新别的字段时,本来没有想更新这个字段,但是也会把这个字段更新为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时不更新。

优化:

还是使用lambdaupdatewrapper的set更新,方法update(entity, updatewrapper)当第一个参数实体类entity不为null时,其中entity中为null的属性不会更新,不为null的会更新, updatewrapper.set()是不论是否为null都更新。
既可以携程:

	 lambdaupdatewrapper<userentity> updatewrapper = wrappers.lambdaupdate();
	 if (stringutils.isempty(phone)) {
	 		// 这个值为null,才set,不然sql里面会两次赋值,执行sql时报错
	 		updatewrapper.set(userentity::getphone, null);
	 }
	 updatewrapper.eq(userentity::getuserid, "0001");
	 userentity entity = new userentity();
	 entity.setname("张三");
	 entity.setage(null);
	 usermapper.update(null, updatewrapper);

说明:根据userid更新,name为张三,phone为null,而age不更新。
sql:

update user set name = '张三', phone = null where user_id = '0001'

结论:使用update(entity, updatewrapper)更新

属性为null不更新,使用entity保存;若属性为null时更新表中字段为null,则用updatewrapper.set()保存数据,set前需要判断这个属性的值为null。

总结

到此这篇关于mybatis-plus更新字段为null两种常用方法及优化的文章就介绍到这了,更多相关mybatis-plus更新字段为null内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com