How to get the SQL String From JPQLQuery

别说谁变了你拦得住时间么 提交于 2020-05-27 05:17:24

问题


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:


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



回答2:


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


来源:https://stackoverflow.com/questions/6412774/how-to-get-the-sql-string-from-jpqlquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!