5

I execute a native query by JPA. My DB is oracle and I have a Clob column. When I get the result, How can I get the clob value from the resultList? I cast it to String and I get ClassCastException. actual object is com.sun.proxy.$Proxy86.

Query query = entityManager.createNativeQuery("Select Value from Condition");
List<Object[]> objectArray =  query.getResultList();
for (Object[] object : objectArray) {
     ???
}
Ram
  • 1,743
  • 2
  • 18
  • 40
Hamid
  • 153
  • 1
  • 2
  • 9
  • Possible duplicate of [how to Retrive the CLOB value from Oracle using java](https://stackoverflow.com/questions/19486648/how-to-retrive-the-clob-value-from-oracle-using-java) – Hadi J Mar 03 '18 at 08:20
  • @HadiJ By JPA, not JDBC. – Hamid Mar 03 '18 at 08:25

2 Answers2

11

You can use java.sql.Clob

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

Clob object has type proxy so convert it by the following method to 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();

}
Ali Esmaily
  • 801
  • 6
  • 6