### Error updating database. Cause: java.lang.IllegalStateException: Type handler was null on parameter mapping for property 'params'. It was either not specified and/or could not be found for the javaType (java.util.Map) : jdbcType (null) combination.
### The error may exist in com/cn/xxx/mapper/xxxx.java (best guess)
### The error may involve com.cn.xxx.mapper.xxxx.insert
### The error occurred while executing an update
### Cause: java.lang.IllegalStateException: Type handler was null on parameter mapping for property 'params'. It was either not specified and/or could not be found for the javaType (java.util.Map) : jdbcType (null) combination.
这是我执行this.saveBatch(devices);时报的错误,然后查了一下,问题的根本原因在于 MyBatis 无法为 params
属性(类型为 Map<String, Object>
)找到合适的类型处理器(Type Handler)。这是因为 MyBatis 默认不支持直接将 Map
类型作为参数传递给 SQL 语句。我寻思我写表实体的时候也没传Map类型呀,然后我点进去一看,发现了它继承了一个BaseEntity类。而这个父类里面定义了这个属性。
问题找到了,那就好解决了。
方法:修改实体类,避免直接使用 Map
public class xxxx extends BaseEntity {
private String paramsJson; // 存储 JSON 字符串
public Map<String, Object> getParams() {
if (paramsJson == null) {
return null;
}
try {
// ObjectMapper 是 Jackson 库的核心类,用于处理 JSON 数据的序列化和反序列化。它提供了多种方法来将 Java 对象转换为 JSON 字符串,以及将 JSON 字符串转换为 Java 对象
// 使用 Jackson 库将 JSON 字符串反序列化为 Map<String, Object> 类型的代码
return new ObjectMapper().readValue(paramsJson, Map.class);
} catch (Exception e) {
throw new RuntimeException("Failed to parse JSON", e);
}
}
public void setParams(Map<String, Object> params) {
if (params == null) {
this.paramsJson = null;
} else {
try {
// 将 params(一个 Map 类型的对象)转换为 JSON 格式的字符串,并将其存储在 paramsJson 字段中
this.paramsJson = new ObjectMapper().writeValueAsString(params);
} catch (Exception e) {
throw new RuntimeException("Failed to serialize JSON", e);
}
}
}
}