数据库中的某个字段是CLOB类型的,我在查询某个SQL的时候,用Map<String,Object>来接。就会报错。
解决办法:
- 创建一个自定义处理类:
@MappedTypes 定义的是 JavaType 类型,可以指定哪些 Java 类型被拦截。
@MappedJdbcTypes 定义的是 JdbcType 类型,它需要满足枚举类 org.apache.ibatis.type.JdbcType 所列的枚举类型。
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import java.io.StringReader;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Clob;
/**
* 自定义处理 JdbcType.Blob 和 java Object(String)
* 处理转 json 报错,将 oracle.sql.Clob 类型转为 String 类型
* copy org.apache.ibatis.type.ClobTypeHandler 类的处理
*/
@MappedTypes({Object.class})
@MappedJdbcTypes(value = {JdbcType.CLOB})
public class ClobTypeHandler extends BaseTypeHandler<Object> {
@Override
public void setNonNullParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException {
String parameterStr = (String) parameter;
StringReader reader = new StringReader(parameterStr);
ps.setCharacterStream(i, reader, parameterStr.length());
}
@Override
public Object getNullableResult(ResultSet rs, String columnName) throws SQLException {
String value = "";
Clob clob = rs.getClob(columnName);
if(clob != null) {
int size = (int)clob.length();
value = clob.getSubString(1L, size);
}
return value;
}
@Override
public Object getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
String value = "";
Clob clob = rs.getClob(columnIndex);
if(clob != null) {
int size = (int)clob.length();
value = clob.getSubString(1L, size);
}
return value;
}
@Override
public Object getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
String value = "";
Clob clob = cs.getClob(columnIndex);
if(clob != null) {
int size = (int)clob.length();
value = clob.getSubString(1L, size);
}
return value;
}
}
- 把上面的ClobTypeHandler注册到mybatis中:
@Configuration
@MapperScan(value={"org.jeecg.modules.**.mapper*"})
public class MybatisPlusSaasConfig {
@Bean
public ConfigurationCustomizer configurationCustomizer() {
return configuration -> {
configuration.getTypeHandlerRegistry().register(Object.class, ClobTypeHandler.class);
};
}
}