I have a use case where I want to get NativeSQL query from TypedQuery or CriteriaQuery before executing that query. I tried one method which partially worked, it is giving SQL string but with placeholders(?) instead of actual values.
Here is the code I used
String hqlQueryString=typedQuery.unwrap(org.hibernate.query.Query.class).getQueryString();
ASTQueryTranslatorFactory queryTranslatorFactory = new ASTQueryTranslatorFactory();
SessionImplementor hibernateSession = entityManager.unwrap(SessionImplementor.class);
QueryTranslator
queryTranslator = queryTranslatorFactory.createQueryTranslator("", hqlQueryString, java.util.Collections.EMPTY_MAP, hibernateSession.getFactory(), null);
queryTranslator.compile(java.util.Collections.EMPTY_MAP, false);
String sqlQueryString = queryTranslator.getSQLString();
Query It gave
select product0_.product_id as col_0_0_, product0_.title as col_1_0_, image1_.url as col_2_0_ from shopify_products product0_ cross join shopify_images image1_ cross join shopify_collections collection2_ where product0_.product_id=image1_.product_id and image1_.product_id=collection2_.product_id and (product0_.product_id in (?)) and collection2_.title=? order by product0_.product_id asc
Is there any way to get final SQL query as string which I can directly execute on Database without any further modification