How to convert HQL to SQL Query programmatically (without logging)

user2707882 picture user2707882 · Aug 22, 2013 · Viewed 29.1k times · Source

I am executing the following HQL and it is executing properly

String hql = "FROM Employee";
Query query = session.createQuery(hql);
List results = query.list();

Now, I also want to log the sql generated at the backend in logs for support users.

I want to make use of QueryTranslator please advise how can I generate the sql for the corresponding HQL please advise how to achieve this.

Answer

Abolfazl Hashemi picture Abolfazl Hashemi · Oct 20, 2014

You can use hibernate QueryTranslator:

String hqlQueryString = hqlQuery.getQueryString();
ASTQueryTranslatorFactory queryTranslatorFactory = new ASTQueryTranslatorFactory();
SessionImplementor hibernateSession = entityManager.unwrap(SessionImplementor.class);
QueryTranslator queryTranslator = queryTranslatorFactory.createQueryTranslator("", hqlQueryString, java.util.Collections.EMPTY_MAP, hibernateSession.getFactory());
queryTranslator.compile(java.util.Collections.EMPTY_MAP, false);
String sqlQueryString = queryTranslator.getSQLString();