现象
使用mybatis-plus 3.5.9版本中LambdaUpdateWrapper set(R column, Object value),当value为null时无法更新
报错如下
Caused by: org.apache.ibatis.type.TypeException:
Could not set parameters for mapping:
ParameterMapping{property='ew.paramNameValuePairs.MPGENVAL4', 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 #4 with JdbcType OTHER .
Try setting a different JdbcType for this parameter or a different jdbcTypeForNull configuration property.
Cause: java.sql.SQLException: 无效的列类型: 1111
上述是Oracle
报的错,Mysql
下却能正常更新
问题分析
org.apache.ibatis.type.BaseTypeHandler
类中方法
@Override
public void setParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException {
if (parameter == null) {
if (jdbcType == null) {
throw new TypeException("JDBC requires that the JdbcType must be specified for all nullable parameters.");
}
try {
ps.setNull(i, jdbcType.TYPE_CODE);
} catch (SQLException e) {
throw new TypeException("Error setting null for parameter #" + i + " with JdbcType " + jdbcType + " . "
+ "Try setting a different JdbcType for this parameter or a different jdbcTypeForNull configuration property. "
+ "Cause: " + e, e);
}
} else {
try {
setNonNullParameter(ps, i, parameter, jdbcType);
} catch (Exception e) {
throw new TypeException("Error setting non null for parameter #" + i + " with JdbcType " + jdbcType + " . "
+ "Try setting a different JdbcType for this parameter or a different configuration property. "
+ "Cause: " + e, e);
}
}
}
中ps.setNull(i, jdbcType.TYPE_CODE);
中jdbcType
为Other
public enum JdbcType {
......
OTHER(Types.OTHER),
......
}
报错信息即为无效类型:1111
解决方案
- 使用
MySQL
数据库
这种有点不太现实,但自己研究还是可以的
目前支持Other
的数据库有PostgreSQL
,MySQL
,SQLServer
- 目前
Mybatis-Plus
3.x版本以上支持LambdUpdate
方式更新null
字段 - 配置更新策略
全局配置:
mybatis-plus:
global-config:
field-strategy: IGNORE
使用注解
FieldStrategy insertStrategy() default FieldStrategy.DEFAULT;
/**
* 字段验证策略之 update: 当更新操作时,该字段拼接set语句时的策略
* <p>
* IGNORED: 直接拼接 update table_a set column=#{columnProperty}, 属性为null/空string都会被set进去
* NOT_NULL: update table_a set <if test="columnProperty != null">column=#{columnProperty}</if>
* NOT_EMPTY: update table_a set <if test="columnProperty != null and columnProperty!=''">column=#{columnProperty}</if>
* NOT_EMPTY 如果针对的是非 CharSequence 类型的字段则效果等于 NOT_NULL
*
* @since 3.1.2
*/
FieldStrategy updateStrategy() default FieldStrategy.DEFAULT;
若只针对指定字段需要指定的jdbcType
4. 若字段为null
直接赋值空串