~/home of geeks

Hibernate HQL to SQL Translation

· 155 Wörter · 1 Minute(n) Lesedauer

hall full of ice figures, sci-fi

For debugging purposes using hibernate it’s often usefull to have the generated SQL query to an appropriate HQL query. But setting the hibernate configuration hibernate.show_sql to true leads to logging any query made within an application (which can be a lot in some applications). With the following class the hibernate API is used to generate the correct SQL query from a given HQL query and can be used anywhere to log the generated query.

Of course, for that work to be done, the class needs a reference to the SessionFactory.

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;

public class HqlToSqlTranslator {
  private SessionFactory sessionFactory;
  
  public void setSessionFactory(SessionFactory sessionFactory){
    this.sessionFactory = sessionFactory;
  }

  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.
        createQueryTranslator(
          hqlQueryText, 
          hqlQueryText, 
          Collections.EMPTY_MAP, factory
        );
      translator.compile(Collections.EMPTY_MAP, false);
      return translator.getSQLString(); 
    }
    return null;
  }
}