How to get the clob value from the resultList of jpa native query?
Asked Answered
T

2

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) {
     ???
}
Terrarium answered 3/3, 2018 at 8:13 Comment(2)
Possible duplicate of how to Retrive the CLOB value from Oracle using javaSlight
@HadiJ By JPA, not JDBC.Terrarium
N
12

You can use java.sql.Clob

for (Object[] object : objectArray) {
       Clob clob = (Clob)object[0];
       String value = clob.getSubString(1, (int) clob.length());
}
Nettle answered 4/3, 2018 at 8:38 Comment(1)
Thanks. This was a much more simpler solutionAddendum
S
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();

}
Sinless answered 26/8, 2018 at 11:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.