Wednesday, October 26, 2011

Hibernate LazyInitializationException handling

In toString() method you want to output objects that are lazy fetched.
Solution that I use is via reflection with exception catching.
This will work only for fields declared in this class not super!

@Override:
public String toString()
{
   StringBuilder sb = new StringBuilder();
   sb.append(......);
   sb.append(ExceptionHandler.ignoreLazy(this, "zone"));
   return sb.toString();
}

public class ExceptionHandler:
public static String ignoreLazy(Object whom, String property)
{
  try
  {
    Field field = whom.getClass().getDeclaredField(property);
    field.setAccessible(true);
    Object print = field.get(tkoMeSadrzi);
    return print.toString();
 }
 catch (NoSuchFieldException e)
 {
   log.warn("DEVELOPER EXC ", e);
   return "NoSuchFieldException: " + e.getMessage();
  }
  catch (Exception lazy)
  { //ignore
    //log.debug("******* IGNORE LAZY : "+property);
    return "lazy loaded!";
  }
}

Hibernate show sql with parameters


#log hibernate prepared statements/SQL queries 
#(equivalent to setting 'hibernate.show_sql' to 'true')
log4j.logger.org.hibernate.SQL=debug

# log JDBC bind parameter runtime arguments
log4j.logger.org.hibernate.type=trace

To format sql output put this line in hibernate configuration file:
hibernate.format_sql