Hibernate Criteria to SQL Translation

Some time ago I posted a helper-class to transform HQL to SQL for debugging purposes. Meanwhile I found out how also to transform Criterias to SQL.

Please be aware that the solution below seems like a big dirty hack to me.

import java.lang.reflect.Field;
import java.util.Collections;
import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.engine.SessionFactoryImplementor;
import org.hibernate.hql.QueryTranslator;
import org.hibernate.hql.QueryTranslatorFactory;
import org.hibernate.hql.ast.ASTQueryTranslatorFactory;
import org.hibernate.impl.CriteriaImpl;
import org.hibernate.impl.SessionImpl;
import org.hibernate.loader.OuterJoinLoader;
import org.hibernate.loader.criteria.CriteriaLoader;
import org.hibernate.persister.entity.OuterJoinLoadable;
public class HibernateHqlAndCriteriaToSqlTranslator {
  private SessionFactory sessionFactory;
  public void setSessionFactory(SessionFactory sessionFactory){
    this.sessionFactory = sessionFactory;
  public String toSql(Criteria criteria){
      CriteriaImpl c = (CriteriaImpl) criteria;
      SessionImpl s = (SessionImpl)c.getSession();
      SessionFactoryImplementor factory = (SessionFactoryImplementor)s.getSessionFactory();
      String[] implementors = factory.getImplementors( c.getEntityOrClassName() );
      CriteriaLoader loader = new CriteriaLoader((OuterJoinLoadable)factory.getEntityPersister(implementors[0]),
        factory, c, implementors[0], s.getEnabledFilters());
      Field f = OuterJoinLoader.class.getDeclaredField("sql");
      return (String) f.get(loader);
    catch(Exception e){
      throw new RuntimeException(e); 
  public String toSql(String hqlQueryText){
    if (hqlQueryText!=null && hqlQueryText.trim().length()>0){
      final QueryTranslatorFactory translatorFactory = new ASTQueryTranslatorFactory();
      final SessionFactoryImplementor factory = 
        (SessionFactoryImplementor) sessionFactory;
      final QueryTranslator translator = translatorFactory.
          Collections.EMPTY_MAP, factory
      translator.compile(Collections.EMPTY_MAP, false);
      return translator.getSQLString(); 
    return null;
Tags:, , ,

3 Responses to “Hibernate Criteria to SQL Translation” »»

  1. Comment by rvltng_hbrntr | 1:25 15.01.11|X

    works great, thanks, any chance to get the sql populated with the params

  2. Comment by Fred | 21:05 07.02.12|X

    Very good. works fine !!

  3. Comment by SRT | 12:10 19.03.12|X

    does not provide the parameters. Any idea on how to get that?

Leave a Reply »»

Note: All comments are manually approved to avoid spam. So if your comment doesn't appear immediately, that's ok. Have patience, it can take some days until I have the time to approve my comments.