Cause: java.sql.SQLException: No value specified for parameter 4
问题
执行更新sql时报错,异常栈如下
org.springframework.jdbc.BadSqlGrammarException:
### Error updating database. Cause: java.sql.SQLException: No value specified for parameter 4
### The error may exist in com/my/mapper/MyMapper.java (best guess)
### The error may involve com.my.mapper.MyMapper.updateById-Inline
### The error occurred while setting parameters
### SQL: UPDATE my_table SET col1=?, col2=?, col3=?, col4=? WHERE id=?
### Cause: java.sql.SQLException: No value specified for parameter 4
; bad SQL grammar []; nested exception is java.sql.SQLException: No value specified for parameter 4
Statement [truncated]: UPDATE my_table SET col1='xxx',\ncol2='',\ncol3='',\n\n\ncol4=null
注意,占位符索引是从1开始的,所以这里的parameter 4,是col4;提示信息是未设置col4;
col4字段,数据类型是个json格式的字符串,数据类型是varchar(设置为json更合理),为了查询出来字符串自动转为对象;更新数据时,将对象转为字符串;所以自定义了Mybatis的BaseTypeHandler
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
@MappedJdbcTypes({JdbcType.LONGVARCHAR})
@MappedTypes({List.class})
public class CustomTypeHandler extends BaseTypeHandler<List<CustomInfo>> {
@Override
public void setNonNullParameter(PreparedStatement preparedStatement, int i, List<CustomInfo> customInfos, JdbcType jdbcType) throws SQLException {
if (customInfos == null || customInfos.isEmpty() || !JdbcType.LONGVARCHAR.equals(jdbcType)) {
return;
}
String str = JSON.toJSONString(customInfos);
preparedStatement.setString(i, str);
}
}
解决
根据提示信息,自然而然的就知道,需要设置下值
修改后
if (customInfos == null || customInfos.isEmpty() || !JdbcType.LONGVARCHAR.equals(jdbcType)) {
//没有值或者空集合,根据实际情况,设置为null
preparedStatement.setString(i,null);
return;
}