Search code examples
javaeclipselinkjpql

Getting the JPQL/SQL String Representations for a Criteria Query


How to Getting the SQL String Representations for a Criteria Query with parmetervalue ?

I tried this but it returns a string to me without the parameter values:

String QueryString = 'SELECT * FROM CUSTOMERS WHERE lastname = ?'


query = entityManager.createNativeQuery(QueryString);

query.setParameter(1, "toto");

System.out.print(query.unwrap(JpaQuery.class).getDatabaseQuery().getSQLString());

But returns "SELECT * FROM CUSTOMERS WHERE lastname = ?" instead of "SELECT * FROM CUSTOMERS WHERE lastname = 'toto'"


Solution

  • Thanks to @GrootCfor helping me find the solution.

    If it helps other people here is the solution:

    String QueryString = 'SELECT * FROM CUSTOMERS WHERE lastname = ?';
    Query query = entityManager.createNativeQuery(QueryString); 
    Session session = entityManager.unwrap(JpaEntityManager.class).getActiveSession();  
    DatabaseQuery databaseQuery = query.unwrap(org.eclipse.persistence.jpa.JpaQuery.class).getDatabaseQuery();
    DatabaseRecord recordWithValues= new DatabaseRecord();
    
    query.setParameter(1, "toto"); 
    recordWithValues.add(new DatabaseField(Integer.toString(1)), "toto");
    
    databaseQuery.prepareCall(session, recordWithValues); 
    String sqlStringWithArgs = databaseQuery.getTranslatedSQLString(session, recordWithValues);
    
    System.out.print(sqlStringWithArgs);
    
    ====SELECT * FROM CUSTOMERS WHERE lastname = 'toto'====