如何从jpa本机查询的resultList中获取clob值?

问题描述 投票:3回答:2

我通过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
2个回答
5
投票

您可以使用java.sql.Clob

for (Object[] object : objectArray) {
       Clob clob = (Clob)object[0];
       String value = clob.getSubString(1, (int) clob.length());
}

2
投票

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();

}
© www.soinside.com 2019 - 2024. All rights reserved.