JPQL query convert to SQL query

12,259

Solution 1

I found the answer for Hibernate HQL queries;

final Query query = sessionFactory.getCurrentSession().createQuery(hql);

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

Thanks to:

http://good-old-mushroom-called-bedla.blogspot.com/2012/04/how-to-convert-hql-to-sql-in-hibernate.html

Solution 2

There will be no JPA standard way to get the SQL. The EclipseLink specific solution is available in EclipseLink's FAQ http://wiki.eclipse.org/EclipseLink/FAQ/JPA#How_to_get_the_SQL_for_a_Query.3F

Share:
12,259
Oleksandr Samsonov
Author by

Oleksandr Samsonov

Updated on July 13, 2022

Comments

  • Oleksandr Samsonov
    Oleksandr Samsonov almost 2 years

    Is it possible to convert JPQL query to SQL and save this query to database?

    I want to write JPQL queries when developing program. But whet will deploy application to server I need compile querys to native SQL depends on DB.

  • mujib ishola
    mujib ishola almost 7 years
    This feature should will be added to new version of JPA spec.
  • Krish
    Krish about 6 years
    @oleksandr-samsonov How to do it for JPQL using Spring Data JPA ?