简体   繁体   中英

How can I get Toplink generated query by using getTranslatedSQLString?

So what I'm doing is creating a subquery that gets a list of ID values, then the main query gets all the necessary values and adds ordering.

What I have is this:

ReportQuery querySub = new ReportQuery(Predmet.class, generatedExpression);
querySub.addAttribute("m_id");

DatabaseRow row = new DatabaseRow();
querySub.prepareCall(getSession(), row);

// This part is the problem
String sql = querySub.getTranslatedSQLString(getSession(), row);

The problem with this code is that it doesn't return TranslatedSQLString, it returns the same result as querySub.getSQLString() . Now in all the example code I saw, they either instanced row as a new object or didn't bother to write from where they got the reference but whatever the case, this doesn't work (TopLink version issue?). I'm guessing I need to populate the DatabaseRow object myself, but I can't find any example online.

you need get session like this:

JpaHelper.getDatabaseSession(getEntityManager().getEntityManagerFactory());

The Database that you need is:

TypedQuery<T> typedQuery = getEntityManager().createQuery(cq);
DatabaseQuery databaseQuery = typedQuery.unwrap(JpaQuery.class).getDatabaseQuery();

So the final example is:

Session session = JpaHelper.getDatabaseSession(getEntityManager().getEntityManagerFactory());
DatabaseQuery databaseQuery = null;
if(typedQuery instanceof EJBQueryImpl)
    databaseQuery = ((EJBQueryImpl<T>)typedQuery).getDatabaseQuery();
else
    databaseQuery = typedQuery.unwrap(JpaQuery.class).getDatabaseQuery();
sql = databaseQuery.getTranslatedSQLString(session, databaseQuery.getTranslationRow());

That work for me.

I didn't manage to find any way to do this by using getTranslatedSQLString. I suppose the DatabaseRow needs to be populated, but I have yet to find the proper way. For now, I'm using "bruteforce" substitution, I "memorize" all of my parameters and do a find/replace on each "?" sign in the query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM