Query.getReturnAliases() best alternative


Query.getReturnAliases() method is deprecated since Hibernate 5.2. According to the documentation an alternative is to make use of javax.persistence.Tuple to retrieve the aliases.

But one of the advantages of using getReturnAliases() is that it the underlying query was not executed to retrieve the aliases. By using the Tuple based approach I need to execute the query first in order to retrieve the aliases. See the following code snippets as an example:

With getReturnAliases():

final String[] queryAliases = session.createQuery(hqlQuery).getReturnAliases();

With Tuple Query:

 Query<Tuple> query = session.createQuery(hqlQuery), Tuple.class);
 for (TupleElement<?> tupleElement : query.uniqueResult().getElements()) {
   queryAliases[i] = tupleElement.getAlias();

Do you know if there exists another approach to retrieve the aliases of a query? Specially if it does not require to execute the query first.


any suggestion? Thank you in advance!

You need to execute the query anyway in order to get the results, so why is there any issue with Tuple?

More, you can use explicit aliases in your SQL query so you already know what aliases to expect.


let me explain the use case: we have a class which receives SQL queries which are defined by users as part of our application metadata, so we do not know which are the aliases defined in the query beforehand.

As part of a dynamic processing we are doing in our class, we used the Query.getReturnAliases() method to just retrieve the aliases. By using this method, we were able to get the aliases without executing the underlying query.

If we now replace that deprecated method and use a Tuple query instead, we are introducing a change in terms of performance in our processing, as previously we did not need to execute the query to retrieve the aliases.

The internal entity query API is going to change massively in 6.0, so I’m sure there was a good reason for deprecating that method.

For the moment, you can simply use it since it’s still available. It might be that even if this method is removed, the underlying mechanism for resolving the aliases might be in place:

final ReturnMetadata metadata = queryPlanCache.getHQLQueryPlan( 
    queryString, false, Collections.EMPTY_MAP )

return metadata == null ? null : metadata.getReturnAliases();

The queryPlanCache will also be replaced by QueryEngine, so keep an eye on 6.0 to see what’s the best way to retrieve this info.

Nevertheless, you can design a DTO that provides both the query and the aliases so that your clients supply both info. If you take this approach, your code will work for both 5.x and 6.x.


thanks for the suggestion! I’ll give it a try.