Hibernate createNativeQuery返回Clob的代理对象

p45*_*p45 3 java sql hibernate clob hibernate-native-query

我被迫进入一种情况,在这种情况下,我正在使用休眠createNativeQuery返回对象数组列表。

我的查询从中返回值的(许多)列之一是CLOB。

返回的对象是com.sun.Proxy对象。

我已经看到了问题,这里 那里

getClass().getInterfaces()
Run Code Online (Sandbox Code Playgroud)

用于标识它是返回的WrappedClob。

但是,鉴于我的Java代码中现在已有此代理对象,如何将其转换为有用的东西(如字符串)?

Anu*_*pam 6

以下代码有助于取消代理

链接对我有帮助,只需在代码中添加一些内容即可 :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();
        }
Run Code Online (Sandbox Code Playgroud)