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());
  }
 }
}

2 komentáře:

  1. I need to do the same for JPQL. Please let me know how I can achieve it ..

    OdpovědětVymazat
  2. You've saved my day, thanks!
    It is also worth to mention how to get sessionFactory.
    To do it you just need this:
    Session session = (Session) entityManager.getDelegate();
    SessionFactory sessionFactory = session.getSessionFactory();

    OdpovědětVymazat