HQL Count Distinct Multiple Columns Alternative
Our normal query execution path is:
1) change query to perform a select count on the query to get paging information established
2) load a page from the query
This works fine when you have something like “select distinct table.id” – just replace the from part of the query to be “select count(distinct table.id)”
Once in a while we have the case of wanting a multiple column distinct, e.g. “select distinct table1.id, table2.other,…” HQL doesn’t let you use multiple columns/objects in a select count distinct.
The first step is to reduce your query from objects as to atomic values. Instead of getting the Address object, just get the Address id. This will be some Integer or other native Java that does not require any materialization (and follow-on Hibernate querying to fulfill due to aggressive loading).
So, now your standard query looks like “select distinct c1, c2, c3, …” where everything being selected is a native Java type.
Here is the leap of faith: just load the entire result set into a List and get the size() of the list. Something like:
Integer size = query.list().size();
Assuming you are performing some limits on the query, say under 20K records I think we are looking at about 50K of space allocated for the List resultset. Further, the execution and transfer of data from the database to Java should be very quick (if not you probably have some work to do to optimize your query in the first place)

