通过 JDBC 查询 CLOB 数据时,可能会遇到返回的对象不是直接的字符串,而是像 dm.jdbc.driver.DmdbNClob
、oracle.sql.CLOB这样的类实例。
在mybatis中直接查询得到的是类实例:
在mybatis中将 CLOB 数据转换为字符串:
结果对比:
转换前:
转换后:
工具类转换方法代码:
public static void transferListMap(List<Map<String, Object>> list) {
try {
if(ObjectKit.isEmpty(list)){
return;
}
for(Map<String,Object> map : list){
transferMap(map);
}
} catch (Exception e) {
throw new ImpException(ImpError.APP_ERR_20_00_01, e);
// return null;
}
}
public static void transferMap(Map<String, Object> map) {
try {
if (ObjectKit.isEmpty(map)) {
}
for (Map.Entry<String, Object> entry : map.entrySet()) {
Object value = entry.getValue();
String key = entry.getKey();
String val = String.valueOf(value);
if (null != value && !"null".equalsIgnoreCase(val) && !"undefined".equals(val)
&& (val.contains(IMP_ENUMS.Nclob.ORACLE_NCLOB.getVal() ) || val.contains(IMP_ENUMS.Nclob.ORACLE_CLOB.getVal())
|| val.toUpperCase().contains(IMP_ENUMS.Nclob.CLOB.getVal()))) {
Clob columnClob = (Clob) value;
boolean isSql = false;
if(key.toUpperCase().indexOf("SQL") != -1){
isSql = true;
}
map.put(entry.getKey(), clob2String(columnClob,isSql));
}
}
} catch (Exception e) {
throw new ImpException(ImpError.APP_ERR_20_00_01, e);
// return null;
}
}
public static String clob2String(Clob clob,boolean isSql) throws SQLException, IOException {
String ret = "";
Reader read = null;
BufferedReader br = null;
try{
read = clob.getCharacterStream();
br = new BufferedReader(read);
String s = br.readLine();
StringBuffer sb = new StringBuffer();
while (s != null) {
sb.append(s);
sb.append(System.lineSeparator());
s = br.readLine();
}
ret = sb.toString();
}finally {
if (br != null) {
br.close();
}
if (read != null) {
read.close();
}
}
return ret;
}