默认情况下,mybatis将oracle的Clob类型查询出来,结果是oracle.sql.CLOB@13cda7c9这样的。
下面是将CLOB类型转换成String的方法
首先,添加一个转换的类,实现TypeHandler的接口package xxx.xxx;
import java.io.IOException;
import java.io.Reader;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;
public class OracleClobTypeHandlerCallback implements TypeHandler {
public Object valueOf(String param) {
return null;
}
@Override
public Object getResult(ResultSet rs, String columnName) throws SQLException {
java.sql.Clob s = rs.getClob(columnName);
if (rs.wasNull()) {
return "";
}
else {
String clobStr = "";
Reader inStream = s.getCharacterStream();
char[] c = new char[(int) s.length()];
try {
inStream.read(c);
clobStr = new String(c);
inStream.close();
}
catch (IOException e) {
e.printStackTrace();
}
return clobStr;
}
}
@Override
public Object getResult(ResultSet arg0, int arg1) throws SQLException {
return null;
}
@Override
public Object getResult(CallableStatement arg0, int arg1) throws SQLException {
return null;
}
@Override
public void setParameter(PreparedStatement arg0, int arg1, Object arg2, JdbcType arg3) throws SQLException {
java.sql.Clob clob = null;
try {
if (arg2 == null) {
arg2 = "";
}
clob = new javax.sql.rowset.serial.SerialClob(arg2.toString().toCharArray());
}
catch (Exception e) {
}
arg0.setClob(arg1, clob);
}
}
然后,在mybatis的config文件中添加typeHandler
这样,在遇到Clob类型的时候,就能转换成String了。
另外,如果mapper中返回类型设置的是HashMap,那么,就需要返回为List>
然后,遍历这个集合,将java.sql.Clob这个类型手动转换为String,转换方式为public static String Clob2String(java.sql.Clob clob) {
String clobStr = "";
try {
Reader inStream = clob.getCharacterStream();
char[] c = new char[(int) clob.length()];
inStream.read(c);
clobStr = new String(c);
inStream.close();
} catch (IOException e) {
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return clobStr;
}