Hibernate recursive initialization

后端 未结 2 1620
孤街浪徒
孤街浪徒 2021-01-01 16:54

i am writing one function in hibernate to recursively initialize all properties of object recursively so whole object graph is loaded.

i have two complex scenarios w

2条回答
  •  说谎
    说谎 (楼主)
    2021-01-01 17:29

    Full code:

    public  T recursiveInitliaze(T obj) {
        Set dejaVu = Collections.newSetFromMap(new IdentityHashMap());
        try {
            recursiveInitliaze(obj, dejaVu);
        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            ReflectionUtils.handleReflectionException(e);
        }
        return obj;
    }
    
    private void recursiveInitliaze(Object obj, Set dejaVu) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
        if (dejaVu.contains(this)) {
            return;
        } else {
            dejaVu.add(this);
    
            if (!Hibernate.isInitialized(obj)) {
                Hibernate.initialize(obj);
            }
            PropertyDescriptor[] properties = PropertyUtils.getPropertyDescriptors(obj);
            for (PropertyDescriptor propertyDescriptor : properties) {
                Object origProp = PropertyUtils.getProperty(obj, propertyDescriptor.getName());
                if (origProp != null) {
                    this.recursiveInitliaze(origProp, dejaVu);
                }
                if (origProp instanceof Collection && origProp != null) {
                    for (Object item : (Collection) origProp) {
                        this.recursiveInitliaze(item, dejaVu);
                    }
                }
            }
        }
    }
    
    
    

    Code of ReflectionUtils:

    /**
     * Handle the given reflection exception. Should only be called if no
     * checked exception is expected to be thrown by the target method.
     * 

    Throws the underlying RuntimeException or Error in case of an * InvocationTargetException with such a root cause. Throws an * IllegalStateException with an appropriate message else. * @param ex the reflection exception to handle */ public static void handleReflectionException(Exception ex) { if (ex instanceof NoSuchMethodException) { throw new IllegalStateException("Method not found: " + ex.getMessage()); } if (ex instanceof IllegalAccessException) { throw new IllegalStateException("Could not access method: " + ex.getMessage()); } if (ex instanceof InvocationTargetException) { handleInvocationTargetException((InvocationTargetException) ex); } if (ex instanceof RuntimeException) { throw (RuntimeException) ex; } throw new UndeclaredThrowableException(ex); }

    提交回复
    热议问题