viernes, 29 de enero de 2010

Show SQL from Hibernate Criteria

Sometimes you need to show the SQL generated by your Hibernate Criteria. I have found one way to get it easily,

public static void showSql(Criteria c){
if( log.isDebugEnabled()){
long init = System.currentTimeMillis();
CriteriaImpl critImpl = ((CriteriaImpl)c);

try{
SessionImpl s = (SessionImpl)critImpl.getSession();
SessionFactoryImplementor factory = (SessionFactoryImplementor)s.getSessionFactory();
String[] implementors = factory.getImplementors( critImpl.getEntityOrClassName() );
CriteriaLoader loader = new CriteriaLoader((OuterJoinLoadable)factory.getEntityPersister(implementors[0]),
factory, critImpl, implementors[0], s.getEnabledFilters());
Field f = OuterJoinLoader.class.getDeclaredField("sql");
f.setAccessible(true);
String sql = (String)f.get(loader);
log.debug("SQL ("+(System.currentTimeMillis()-init) + "ms): " + sql );

}catch(Exception e){


}
}

}

No hay comentarios:

Publicar un comentario