### Question:
SQLExtractor { public static String from(Query query) { AbstractQueryImpl abstractQuery = query.unwrap(AbstractQueryImpl.class); SessionImplementor session = ReflectionUtils.getFieldValue(abstractQuery, "session"); String[] sqls = session.getFactory() .getQueryPlanCache() .getHQLQueryPlan(abstractQuery.getQueryString(), false, Collections.<String, Filter>emptyMap()) .getSqlStrings(); return sqls.length > 0 ? sqls[0] : null; } private  SQLExtractor(); static String from(Query query);  }### Answer:
@Test public void testJPQL() { doInJPA(new JPATransactionFunction<Void>() { @Override public Void apply(EntityManager entityManager) { Query query = 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(query); assertNotNull(sql); LOGGER.info("SQL query: {}", sql); return null; } }); }
@Test public void testCriteriaAPI() { doInJPA(new JPATransactionFunction<Void>() { @Override public Void apply(EntityManager 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"); Path<String> postTitle = post.get("title"); criteria.where( builder.like(postTitle, "%Java%") ); criteria.orderBy( builder.asc(postComment.get("id")) ); Query query = entityManager.createQuery(criteria); String sql = SQLExtractor.from(query); assertNotNull(sql); LOGGER.info("SQL query: {}", sql); return null; } }); }