I’ve got a query using distinct and maxResults on an entity with jpql:
Query q = session.createQuery("select distinct idTypeConfig from TMIDTypeConfig idTypeConfig");
if (maxResults != null) q.setMaxResults(maxResults);
List<TMIDTypeConfig> results = q.list();
When this executes, the sql generated is:
21 Dec 2022 17:22:33,078 DEBUG [SQL [Session#2835de0c] main] select distinct top (?) t1_0.ID_TYPE_PK,t1_0.CFIND_ISSUER,t1_0.CREATED_DATE_TIME,t1_0.DESCRIPTION,t1_0.LAST_UPDATED_DATE_TIME,t1_0.NAME from CFG_ID_TYPE_T t1_0 order by @@version
This causes an exception:
Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: ORDER BY items must appear in the select list if SELECT DISTINCT is specified.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:262) ~[mssql-jdbc-8.2.1.jre11.jar:?]
at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1632) ~[mssql-jdbc-8.2.1.jre11.jar:?]
because hibernate adds “order by @@version” to the generated SQL when using maxResults();
Is there a way to prevent this? Or is there some other workaround?
The entity in here is simple, and this query doesn’t need the distinct, but the actual case where I found this in is more complicated, and the query joins to related entities, so the distinct is necessary.