Skip to content

Instantly share code, notes, and snippets.

@delphym
Last active October 26, 2023 02:14
Show Gist options
  • Save delphym/d90a5d878bd16d4951a3a771289e6a50 to your computer and use it in GitHub Desktop.
Save delphym/d90a5d878bd16d4951a3a771289e6a50 to your computer and use it in GitHub Desktop.
JPA to NATIVE SQL
import javax.persistance.TypedQuery;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory;
import org.hibernate.hql.spi.QueryTranslator;
public class JpaToSQL {
TypedQuery<T> query = null;
public static void main(String[] args) {
query = entityManager.createQuery(queryString.toString(), type);
getNativeSQL(query);
}
public String getNativeSQL(TypedQuery<t> query) {
String hqlQueryString = query.unwrap(org.hibernate.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();
System.out.println(sqlQueryString);
query.getParameters().forEach(p -> System.out.println(p.getName() + ": '" + query.getParameterValue(p.getName()) + "'"));
/*
//SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // It is not a thread safe, use DateTimeFormatter instead
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String queryS = queryString.toString().replaceFirst("\\?", "'" + query.getParameterValue("employeeId").toString() + "'");
queryS = queryS.replaceFirst("\\?", "'" + query.getParameterValue("todo").toString() + "'");
queryS = queryS.replaceFirst("\\?", "'" + dtf.format(((Date) query.getParameterValue("startDate")).toInstant().atZone(ZoneId.systemDefault()).toLocalDate()) + "'");
queryS = queryS.replaceFirst("\\?", "'" + dtf.format(((Date) query.getParameterValue("endDate")).toInstant().atZone(ZoneId.systemDefault()).toLocalDate()) + "'");
//queryS = queryS.replaceFirst("\\?", "'" + sdf.format((Date) query.getParameterValue("startDate")) + "'");
//queryS = queryS.replaceFirst("\\?", "'" + sdf.format((Date) query.getParameterValue("endDate")) + "'");
queryS = queryS.replaceFirst("\\?", "'" + query.getParameterValue("leaveEventTypeName").toString() + "'");
System.out.println(queryS);
*/
System.out.println("XXX");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment