Get SQL query from Query (QuerySqmImpl)

Hi everyone!

I need to get the SQL that would be executed by a Query (QuerySqmImpl). In Hibernate 5 I used a QueryTranslator, but that class doesn’t seem to be available anymore.

I’m using an idea based on a library I’ve found called “hypersistence”, but it calls a private method called “ConcreteSqmSelectQueryPlan.buildCacheableSqmInterpretation”. The idea works, but I have to create a copy of the original Query, or else I get a NullPointerException at SqmUtil:

final SqmParameter<?> expansionSqmParam = expansions.get( expansionPosition++ );
final List<JdbcParametersList> jdbcParamBinds = jdbcParamMap.get( expansionSqmParam );
for ( int i = 0; i < jdbcParamBinds.size(); i++ ) {

At that point, jdbcParamBinds is null if you call the method twice with the same Query.

As I said, it works, but it’s using internal methods that we should not be using. Is there any other cleaner, nicer approach for this task? I’ve searched the documentation and the internet, but so far without success.

Best regards.

There is no clean approach to this because there might be multiple SQL queries (multi-table DML) and the SQL translation itself might depend on parameter bindings. Hibernate ORM tries to avoid over-promising on APIs/SPIs so that it can improve internals later.

If you’re curious, Blaze-Persistence works with the SQL of the Hibernate queries as well. You can take a look at how it does that here:

Will do. Thank you very much for the tip.

As for me, it’s mainly for logging for helping developers and errors, so if the SQL is not 100% perfect it’s not a problem, and as I said it’s working fine.

Thanks and keep the good work on!