středa 4. dubna 2012

How to convert HQL to SQL in Hibernate

If you want to get native SQL from HQL in Hibernate you can use following snippet.

final Query query = sessionFactory.getCurrentSession().createQuery(hql).setParameter(paramName, paramValue);

final QueryTranslatorFactory ast = new ASTQueryTranslatorFactory();
final QueryTranslatorImpl newQueryTranslator = (QueryTranslatorImpl) ast.createQueryTranslator(queryId, query.getQueryString(), Collections.EMPTY_MAP, (SessionFactoryImplementor) sessionFactory);
newQueryTranslator.compile(null, false);
sql = newQueryTranslator.getSQLString();

if (youWantToHaveParametersWithTheirNamesNotWithQuestionMarks) {
 final List parameterSpecifications = newQueryTranslator.getCollectedParameterSpecifications();
 if (!CollectionUtils.isEmpty(parameterSpecifications)) {
  for (NamedParameterSpecification parameter : parameterSpecifications) {
   sql = StringUtils.replaceOnce(sql, "?", ":" + parameter.getName());
  }
 }
}