Thursday, March 16, 2017

Hibernate 5.2 upgrade: How to resolve CTE issue

During migration to 5.2.8 you might have come across this issue if you are trying to use CTE (recursive) query. If you try to use setMaxResults, the resulting query turns out to be
 WITH someuse TOP(?) fulname ....  
 Here TOP(?) clause was inserted between someusefulname.

The issue is with the Hibernate dialect. I switched to SQLServer2008Dialect but then I had to again switch to
 org.hibernate.dialect.SQLServer2012Dialect
 because there is better support for pagination in the latest 2012 dialect.
Here is a snapshot of hibernate source which gives insight of how its trying to add pagination support in 2008 dialect.
 if ( selectPos == selectDistinctPos ) {
   // Place TOP after SELECT DISTINCT
   sql.insert( selectDistinctPos + SELECT_DISTINCT.length(), " TOP(?)" );
  }
  else {
   // Place TOP after SELECT
   sql.insert( selectPos + SELECT.length(), " TOP(?)" );
  }

Since my query is a CTE without any select distinct clause in it and on top of that I am using setFirstResult and setMaxResults on NativeQuery, this does not work.

Hopefully, Hibernate team will note this and update their source. Its a beautiful framework close to my heart.

No comments :