MyBatisPlus使用wrapper时更新字段为null时报错解决

前言

当我在使用updateWrapper时,想要将某些字段(此处为fbsj)设成null的时候,

 LambdaUpdateWrapper<DXwDo> updateWrapper = new LambdaUpdateWrapper<>();
 updateWrapper.eq(DXwDo::getId, id);
 updateWrapper.set(DXwDo::getFbsj, null);
 boolean isSuccess = this.update(updateWrapper);

报了一个错误
org.mybatis.spring.MyBatisSystemException:
Error updating database. Cause: org.apache.ibatis.type.TypeException: Could not set parameters for mapping: ParameterMapping{property=‘ew.paramNameValuePairs.MPGENVAL1’, mode=IN, javaType=class java.lang.Object, jdbcType=null, numericScale=null, resultMapId=‘null’, jdbcTypeName=‘null’, expression=‘null’}. Cause: org.apache.ibatis.type.TypeException: Error setting null for parameter #1 with JdbcType OTHER . Try setting a different JdbcType for this parameter or a different jdbcTypeForNull configuration property. Cause: java.sql.SQLException:

数据库使用的是oracle,查了下这是由于oracle对于设null的支持不好,
网上的解决方案是在实体类上设置TableField注解,要么全局改配置

@Data
@TableName("test")
public class DXwDo {
    @TableId
    private Integer id; // id

   // 一开始使用的解决方案
    @TableField(jdbcType = JdbcType.TIMESTAMP)
    private Date fbsj;  // 发布时间
}

但是本人在自己的项目里试了没有效果,

又不想全局设置更新时为null则更新全部,于是试出了一种办法

解决

使用wrapper时将要修改的值设成空字符串""

 
  LambdaUpdateWrapper<DXwDo> updateWrapper = new LambdaUpdateWrapper<>();
 updateWrapper.eq(DXwDo::getId, id);
 // updateWrapper.set(DXwDo::getFbsj, null);
 // 改为如下代码
  updateWrapper.set(DXwDo::getFbsj, "");
 boolean isSuccess = this.update(updateWrapper);

观察数据库记录
执行前
在这里插入图片描述
执行后
在这里插入图片描述
可以看到虽然名义上设成了空字符串“”,但是实际设值会吧数据库记录设成null值
此时会执行sql
update d_xw set fbsj=‘’ where id=‘xxx’;
注意此处我的字段类型为TIMESTAMP,对应的java数据类型为Date(java.util那个),即便不是VARCHAR类型但是仍然可以使用空字符串
亲测使用其他类型,
VARCHAR(对应String)
或者数字类型(如NUMBER(10,0),对应Integer)都是可以生效的。
只要在数据库执行上面的updatesql时能直接设空字符串,则都可以支持