我通过JPA执行本机查询。我的数据库是oracle,我有一个Clob列。当我得到结果时,如何从resultList中获得clob值?我将其转换为String并得到ClassCastException。实际对象是com.sun.proxy。$ Proxy86。
Query query = entityManager.createNativeQuery("Select Value from Condition");
List<Object[]> objectArray = query.getResultList();
for (Object[] object : objectArray) {
???
}
您可以使用java.sql.Clob
for (Object[] object : objectArray) {
Clob clob = (Clob)object[0];
String value = clob.getSubString(1, (int) clob.length());
}
Clob对象具有代理类型,因此可以通过以下方法将其转换为String。
public static String unproxyClob(Object proxy) throws InvocationTargetException, IntrospectionException, IllegalAccessException, SQLException, IOException {
try {
BeanInfo beanInfo = Introspector.getBeanInfo(proxy.getClass());
for (PropertyDescriptor property : beanInfo.getPropertyDescriptors()) {
Method readMethod = property.getReadMethod();
if (readMethod.getName().contains(GET_WRAPPED_CLOB)) {
Object result = readMethod.invoke(proxy);
return clobToString((Clob) result);
}
}
} catch (InvocationTargetException | IntrospectionException | IllegalAccessException | SQLException | IOException exception) {
throw exception;
}
return null;
}
private static String clobToString(Clob data) throws SQLException, IOException {
StringBuilder sb = new StringBuilder();
Reader reader = data.getCharacterStream();
BufferedReader br = new BufferedReader(reader);
String line;
while (null != (line = br.readLine())) {
sb.append(line);
sb.append("\n");
}
br.close();
return sb.toString();
}