【问题标题】:How to get the clob value from the resultList of jpa native query?如何从 jpa 原生查询的 resultList 中获取 clob 值?
【发布时间】:2018-08-11 10:27:00
【问题描述】:

我通过 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


【解决方案1】:

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

}

【讨论】:

    【解决方案2】:

    您可以使用java.sql.Clob

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

    【讨论】:

    • 谢谢。这是一个更简单的解决方案
    猜你喜欢
    • 2017-11-21
    • 2011-04-05
    • 2011-08-31
    • 1970-01-01
    • 2012-12-30
    • 1970-01-01
    • 2018-11-13
    • 2015-08-24
    • 1970-01-01
    相关资源
    最近更新 更多