I am forced into a situation where i am using hibernate createNativeQuery to return a List of Objects arrays.
One of the (many) columns from which my query returns values is a CLOB.
The Object which is returned is com.sun.Proxy object.
I have seen a question here where
getClass().getInterfaces()
was used to identify that it is a WrappedClob being returned.
However given that I now have this proxy object in my Java code, how do I convert it into something useful ... like a String?
The following code helped to unProxy the clob
Link which help me, just add a bit of makeup to the code :D
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Clob;
import java.sql.SQLException;
/**
* Unproxy clob.
*
* @param proxy the proxy
* @return the string
* @throws InvocationTargetException the invocation target exception
* @throws IntrospectionException the introspection exception
* @throws IllegalAccessException the illegal access exception
* @throws SQLException the SQL exception
* @throws IOException Signals that an I/O exception has occurred.
*/
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) {
LOGGER.fatal(exception);
throw exception;
}
return null;
}
/**
* Clob to string.
*
* @param data the data
* @return the string
* @throws SQLException the SQL exception
* @throws IOException Signals that an I/O exception has occurred.
*/
public 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);
}
br.close();
return sb.toString();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With