Wednesday, August 19, 2015

Lazy load exception , Re-using invalid objects

When you get an exception on hibernate session you can not use those objects again.
Their session is invalidated. You must close session and not use objects loaded in that session.
However for some reasons(logging,marking) You need to use them.


What you can do is,load all objects as proxies.
Below code is not complete(reference methods not here) but it is clear and you can easily understand the idea.


    public void refreshBeans( )
    {
        String[ ] beans = this.getBeanNames( ) ;

        for( String beanName : beans )
        {
            YBean val = ( YBean )this.getFieldValue( beanName ) ;

            if( val != null && val.getId( ) != null && val.getId( ).intValue( ) != 0 )
            {
                YBean newbean = HibernateUtils.loadObjectProxyById( ReflectionUtils.getRealBeanClass( val.getClass( ) ), val.getId( ) ) ;
                this.setFieldValue( beanName, newbean ) ;
            }
        }
    }


 

No comments:

Post a Comment