### Question:
SQLExtractor { public static String from(Query query) { AbstractProducedQuery abstractProducedQuery = query.unwrap(AbstractProducedQuery.class); String[] sqls = abstractProducedQuery .getProducer() .getFactory() .getQueryPlanCache() .getHQLQueryPlan(abstractProducedQuery.getQueryString(), false, Collections.emptyMap()) .getSqlStrings(); return sqls.length > 0 ? sqls[0] : null; } private  SQLExtractor(); static String from(Query query);  }### Answer:
@Test public void testJPQL() { doInJPA(entityManager -> { Query jpql = entityManager .createQuery( "select " + " YEAR(p.createdOn) as year, " + " count(p) as postCount " + "from " + " Post p " + "group by " + " YEAR(p.createdOn)", Tuple.class); String sql = SQLExtractor.from(jpql); assertNotNull(sql); LOGGER.info( "The JPQL query: [\n{}\n]\ngenerates the following SQL query: [\n{}\n]", jpql.unwrap(org.hibernate.query.Query.class).getQueryString(), sql ); }); }
@Test public void testCriteriaAPI() { doInJPA(entityManager -> { CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<PostComment> criteria = builder.createQuery(PostComment.class); Root<PostComment> postComment = criteria.from(PostComment.class); Join<PostComment, Post> post = postComment.join("post"); criteria.where( builder.like(post.get("title"), "%Java%") ); criteria.orderBy( builder.asc(postComment.get("id")) ); Query criteriaQuery = entityManager.createQuery(criteria); String sql = SQLExtractor.from(criteriaQuery); assertNotNull(sql); LOGGER.info( "The Criteria API query: [\n{}\n]\ngenerates the following SQL query: [\n{}\n]", criteriaQuery.unwrap(org.hibernate.query.Query.class).getQueryString(), sql ); }); }