Saturday, August 15, 2015

Dump objects in current hibernate session

Sometimes u want to monitor all objects loaded in current hibernate session. For this we get "persistenceContext" from hibernate session. Since it is not visible we played with visibility. Below is a nice very handy piece of code doing this. You can this method at commit of hibernate session to check how many objects loaded during transaction. Most of time you will be very surprised. It will help you to optimize your code.
 public static Object getField( Object instance, String name ) throws Exception
    {
        Field f = instance.getClass( ).getDeclaredField( name ) ;
        f.setAccessible( true ) ;
        return f.get( instance ) ;
    }


public static String printHibernateEntities( )
    {
        final Session s = HibernateManager.getSession( ) ;

        if( s == null )
            return null ;

        StringBuffer sbf = new StringBuffer( ) ;

        List result = null ;
        try
        {
            StatefulPersistenceContext spconContext = ( StatefulPersistenceContext )getField( s, "persistenceContext" ) ;
            Map entities = spconContext.getEntityEntries( ) ;

            result = new ArrayList( entities.size( ) ) ;
            for( Iterator it = entities.values( ).iterator( ); it.hasNext( ); )
            {
                Object o = it.next( ) ;

                String className = ( String )getField( o, "entityName" ) ;

                if( className.indexOf( "." ) > 0 )
                    className = className.substring( className.lastIndexOf( '.' ) + 1, className.length( ) ) ;

                Integer id = ( Integer )getField( o, "id" ) ;

                org.hibernate.engine.EntityEntry e = ( org.hibernate.engine.EntityEntry )o ;

                result.add( className + ": " + id + " = " + o.hashCode( ) + ", key: " + ( e.getId( ) == null ? "N/A" : e.getEntityKey( ) ) + ", status: " + e.getStatus( ) ) ;
            }



            for( int i = 0; i < result.size( ); i++ )
            {

                sbf.append( i + " ) " + result.get( i ) + "\n" ) ;
            }

            if( !FileUtils.isUnix( ) )
            {
                System.out.println( "printHibernateEntities" ) ;
                System.out.println( sbf.toString( ) ) ;
            }
        }
        catch( Exception e )
        {
            e.printStackTrace( ) ;
            YEmergencyEmail.sendErrorMessage( e, "Can not get a dump of printHibernateEntities ", null ) ;
        }

        return sbf.toString( ) ;
    }

1 comment: