iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > JAVA >Mybatis-plus更新字段为null
  • 144
分享到

Mybatis-plus更新字段为null

mybatisjava开发语言 2023-08-19 13:08:52 144人浏览 泡泡鱼
摘要

mybatis-plus更新字段为null 1、在实体类的属性上增加注解:@TableField(updateStrategy = FieldStrategy.IGNORED)2、使用LambdaUpdateWrapper的set更

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

网上比较常用的有两种:

1、在实体类的属性上增加注解:@TableField(updateStrategy = FieldStrategy.IGNORED)

        @TableField(updateStrategy = FieldStrategy.IGNORED)    private String phone;

缺点:当在其它接口更新别的字段时,本来没有想更新这个字段,但是也会把这个字段更新为null。

2、使用LambdaUpdateWrapper的set更新

 // set更新 LambdaUpdateWrapper 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 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。

来源地址:https://blog.csdn.net/chun_hua_xue_yue/article/details/129949435

--结束END--

本文标题: Mybatis-plus更新字段为null

本文链接: https://www.lsjlt.com/news/375459.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作