记Mybatis-Plus更新数据,忽略null值问题

一.问题描述

  近期正在家里美美休假,突然接个电话说是业务反馈生产上要操作置空某个字段,操作之后返回信息是成功,但实际没有反应。于是立刻打开电脑看看什么情况。

public Result<CstGrpInfoDto> edit(@Valid @RequestBody CstGrpInfoDto cstGrpInfoDto) {
       Result<CstGrpInfoDto> result = new Result<CstGrpInfoDto>();
       CstGrpInfo cstGrpInfoEo = cstGrpInfoService.getById(cstGrpInfoDto.getId());
       if (cstGrpInfoEo == null) {
          result.error400("未找到对应实体");
       } else {
          BeanUtils.copyProperties(cstGrpInfoDto, cstGrpInfoEo);
          try {
              cstGrpInfoMapper.updateById(cstGrpInfoEo);
              result.success("修改成功!");
          } catch (Exception e) {
             log.error(e.getMessage(), e);
             result.error400("修改失败!");
          }
       }
       return result;
    }

大致逻辑就是这样,很简单的代码。

一开始想难道是BeanUtils的锅吗?于是DEBUG查看,发现EO的属性值都没有问题,问题只能是在mybatisPlus的updateById方法上。

通过调用查看日志,发现调用updateById方法拼接的SQL中,不包含属性值为null部分的字段.于是推测:mybatisPlus不会修改为null的字段,上网一搜果然是这样。

二.解决方案

方法1 使用UpdateWrapper方式更新

该方法适合明确需要修改的字段。

示例:

public int updateProduct(String productCode) {
        UpdateWrapper<Product> wrapper = new UpdateWrapper<>();
        wrapper.lambda().eq(Product::getProductCode, productCode)
                .set(Product::getName, null);
        return getBaseMapper().update(null, wrapper);
    }

方法2 对某个字段设置单独的field-strategy

根据具体情况,在需要更新的字段中调整验证注解,如下

@TableField(strategy = FieldStrategy.IGNORED)
private String name;

方法3 设置全局的field-strategy (慎用)

import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MybatisPlusConfig {

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 添加分页插件
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        return interceptor;
    }

    @Bean
    public GlobalConfig globalConfig() {
        GlobalConfig globalConfig = new GlobalConfig();
        // 设置全局的更新策略
        GlobalConfig.DbConfig dbConfig = new GlobalConfig.DbConfig();
        dbConfig.setUpdateStrategy(FieldStrategy.IGNORED); // 设置为忽略 null 值
        globalConfig.setDbConfig(dbConfig);
        return globalConfig;
    }
}

properties文件格式:

mybatis-plus.global-config.db-config.update-strategy=ignored

 yml文件格式:

mybatis-plus:
  global-config:
    db-config:
      update-strategy: ignored  # 设置为忽略 null 值

 使用建议:建议根据业务实际情况来选择使用哪种方式,对于有默认值和不可为null的数据,建议使用默认策略

MyBatis-Plus是一个基于MyBatis的简化整合工具,它提供了一些便捷的功能,包括对SQL的自动处理。如果你想要在IN查询中忽略大小写,你可以利用其提供的动态SQL特性。 首先,你需要创建一个包含大小写不敏感比较条件的自定义拦截器或者全局通用Mapper方法。例如,可以创建一个`CaseInsensitiveInInterceptor`: ```java public class CaseInsensitiveInInterceptor implements Interceptor { @Override public Object intercept(Invocation invocation) throws Throwable { ParameterMetaData parameter = invocation.getArgs()[0]; if (parameter != null && parameter.getProperty() != null) { String columnName = parameter.getProperty().getName(); // 这里使用String的toLowerCase()方法将转换为小写 String sql = ((SqlSession sqlSession) invocation.getArgs()[1]).getMapper().buildSqlWithoutParameterMarker(columnName); // 将查询中的所有也转为小写 List<Object> values = new ArrayList<>(invocation.getArgs()[2].size()); for (Object value : invocation.getArgs()[2]) { values.add(value.toString().toLowerCase()); } Object result = sqlSession.selectList(sql, values.toArray()); return result; } return invocation.proceed(); } @Override public Object plugin(Object target) { return Plugin.wrap(target, this); } @Override public void setProperties(Properties properties) { } } ``` 然后,在配置文件中启用这个拦截器: ```xml <plugins> <plugin interceptor="com.example.CaseInsensitiveInInterceptor"/> </plugins> ``` 最后,你在Mapper接口的方法上使用`@GlobalConfig`注解,标该方法需要应用这个拦截器: ```java @GlobalConfig(casesensitiveInStatement = false) List<User> findByPropertyNotIgnoreCase(@Param("property") String property, @Param("values") Collection<String> values); ``` 这样,在`findByPropertyNotIgnoreCase`方法的IN查询中,MyBatis-Plus会自动忽略大小写地匹配
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值