在项目的配置类文件夹中放入如下通用类OracleResultSetInterceptor
import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.plugin.*;import java.io.IOException;
import java.io.Reader;
import java.io.StringWriter;
import java.sql.NClob;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;@Intercepts({@Signature(type = ResultSetHandler.class, method = "handleResultSets", args = { Statement.class })
})
public class OracleResultSetInterceptor implements Interceptor {/*** 用于设置拦截器的属性* 在这里可以根据需要设置拦截器的具体配置,例如通过配置文件传递一些参数或者初始化一些资源* @param properties*/@Overridepublic void setProperties(Properties properties) {}/*** 包装目标对象,返回一个代理对象* @param target 目标对象* @return 代理对象*/@Overridepublic Object plugin(Object target) {return Plugin.wrap(target, this);}/*** 代理对象处理逻辑* @param invocation 包含参数,结果集*/@Overridepublic Object intercept(Invocation invocation) throws Throwable {Object result = invocation.proceed(); // 执行原始方法获取结果if (result instanceof Map) {Map<String, Object> resultMap = (Map<String, Object>) result;processMap(resultMap);}else if(result instanceof List){List<Object> list=(List<Object>)result;for (Object line:list){if(line instanceof Map){processMap((Map<String,Object>)line);}}}return result;}/*** 处理map* @param line* @throws SQLException* @throws IOException*/private void processMap(Map<String,Object> line) throws SQLException, IOException {for (String key:line.keySet()){Object value = line.get(key);if (value instanceof NClob) {NClob nclob = (NClob) value;String nclobString = convertNClobToString(nclob);line.put(key, nclobString);}}}private String convertNClobToString(NClob nclob) throws SQLException, IOException {// 将 NCLOB 数据读取为字符串Reader reader = nclob.getCharacterStream();StringWriter writer = new StringWriter();char[] buffer = new char[1024];int bytesRead;while ((bytesRead = reader.read(buffer)) != -1) {writer.write(buffer, 0, bytesRead);}return writer.toString();}}
配置文件启用mybatis自定义插件
mybatis:configuration:plugins:- interceptor: your.package.CustomResultSetInterceptor
<configuration><plugins><plugin interceptor="your.package.CustomResultSetInterceptor"/></plugins>
</configuration>