【问题标题】:How to get the clob value from the resultList of jpa native query?如何从 jpa 原生查询的 resultList 中获取 clob 值?
【发布时间】:2018-08-11 10:27:00
【问题描述】:
我通过 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
hibernate
jpa
classcastexception
clob
【解决方案1】:
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();
}
【解决方案2】:
您可以使用java.sql.Clob
for (Object[] object : objectArray) {
Clob clob = (Clob)object[0];
String value = clob.getSubString(1, (int) clob.length());
}