How to get the SQL String From JPQLQuery
I'm using EclipseLink.
I've a JPQLquery and I want to get the sql String.. Now I'm doing in this way:
EJBQueryImpl qi = (EJBQueryImpl)jpqlQuery;
String sqlQueryString = qi.getDatabaseQuery().getSQLString();
The problem is that in the sqlQueryString the constant are replaced with ?
I've tried to get the values navigating the expressions trees (getSelectionCriteria()
and getHavingCriteria开发者_开发问答()
) but in this way I loose the type...
Do any one ever have a problem like this one?
Quoted from the EclipseLink FAQ:
To see the SQL for a JPA Query you can enable logging on FINE or lower.
To get the SQL for a specific Query at runtime you can use the DatabaseQuery API.
Session session = em.unwrap(JpaEntityManager.class).getActiveSession();
DatabaseQuery databaseQuery = ((EJBQueryImpl)query).getDatabaseQuery();
databaseQuery.prepareCall(session, new DatabaseRecord());
String sqlString = databaseQuery.getSQLString();
This SQL will contain ? for parameters. To get the SQL translated with the arguments you need a DatabaseRecord with the parameter values.
Session session = em.unwrap(JpaEntityManager.class).getActiveSession();
DatabaseQuery databaseQuery = ((EJBQueryImpl)query).getDatabaseQuery();
String sqlString = databaseQuery.getTranslatedSQLString(session, recordWithValues);
Here is a method that works:
public static void logJpaQuery(EntityManager em, TypedQuery tq){
org.eclipse.persistence.sessions.Session session = em.unwrap(JpaEntityManager.class).getActiveSession();
DatabaseQuery dq = ((EJBQueryImpl) tq).getDatabaseQuery();
AbstractRecord translationRow = dq.getTranslationRow();
dq.prepareCall(session, new DatabaseRecord());
String translatedSQLString = dq.getTranslatedSQLString(session, translationRow);
log.trace("translated sql is: {}", translatedSQLString);
}
精彩评论