io.hypersistence.utils.hibernate.query.SQLExtractor Maven / Gradle / Ivy
Show all versions of hypersistence-utils-hibernate-55 Show documentation
package io.hypersistence.utils.hibernate.query;
import org.hibernate.query.internal.AbstractProducedQuery;
import javax.persistence.Query;
import java.util.Collections;
/**
* The {@link SQLExtractor} allows you to extract the
* underlying SQL query generated by a JPQL or JPA Criteria API query.
*
* For more details about how to use it, check out this article on vladmihalcea.com.
*
* @author Vlad Mihalcea
* @since 2.9.11
*/
public class SQLExtractor {
protected SQLExtractor() {
}
/**
* Get the underlying SQL generated by the provided JPA query.
*
* @param query JPA query
* @return the underlying SQL generated by the provided JPA query
*/
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;
}
}