How to convert a Hibernate proxy to a real entity object

后端 未结 10 796
离开以前
离开以前 2020-11-22 16:49

During a Hibernate Session, I am loading some objects and some of them are loaded as proxies due to lazy loading. It\'s all OK and I don\'t want to turn lazy lo

10条回答
  •  情话喂你
    2020-11-22 17:47

    Thank you for the suggested solutions! Unfortunately, none of them worked for my case: receiving a list of CLOB objects from Oracle database through JPA - Hibernate, using a native query.

    All of the proposed approaches gave me either a ClassCastException or just returned java Proxy object (which deeply inside contained the desired Clob).

    So my solution is the following (based on several above approaches):

    Query sqlQuery = manager.createNativeQuery(queryStr);
    List resultList = sqlQuery.getResultList();
    for ( Object resultProxy : resultList ) {
        String unproxiedClob = unproxyClob(resultProxy);
        if ( unproxiedClob != null ) {
           resultCollection.add(unproxiedClob);
        }
    }
    
    private String unproxyClob(Object proxy) {
        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(proxy.getClass());
            for (PropertyDescriptor property : beanInfo.getPropertyDescriptors()) {
                Method readMethod = property.getReadMethod();
                if ( readMethod.getName().contains("getWrappedClob") ) {
                    Object result = readMethod.invoke(proxy);
                    return clobToString((Clob) result);
                }
            }
        }
        catch (InvocationTargetException | IntrospectionException | IllegalAccessException | SQLException | IOException e) {
            LOG.error("Unable to unproxy CLOB value.", e);
        }
        return null;
    }
    
    private 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();
    }
    

    Hope this will help somebody!

提交回复
热议问题