4

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?

1
  • As a follow up question: how do I get the SQL string when I do a em.persist(pojoDbObject)? Commented Mar 25, 2014 at 15:00

2 Answers 2

4

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);
Sign up to request clarification or add additional context in comments.

2 Comments

What is recordWithValues? Is it possible to get it from DatabaseQuery or EJBQueryImpl?
For future reference: recordWithValues should be databaseQuery.getTranslationRow() (source: dzone.com/articles/eclipselink-how-get-sql)
0

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);
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.