views:

467

answers:

2

I recently had a rather strange phenomenon. Had to obtain a count that included joins over multiple tables with different WHERE conditions. I implemented the query first with the criteria API of hibernate. It correctly created the requested prepared SQL statement but was rather slow. Re-implemented then the entire query using HQL. Was rather nasty to do that but the result performed much faster than with the Criteria API. Does anybody know the reason for that behavior? I assumed that the Criteria and HQL framework use the same code base to transform it to SQL.

A: 

I generally believe that HQL is very near optimal, as it's nearly straight SQL with a few substitutions. I'd assume that the translation from HQL to SQL is just substitution; the Criteria API probably generates HQL to then get transformed. Generally HQL is your best bet.

McWafflestix
+3  A: 

I guess I finally found the reason. It seems that the criteria api creates new variable names each time a prepared statement is executed. The database (in our case, DB2) calculates then a new query execution plan each time the statement is executed. On the other hand, HQL uses the same variable names, allowing the database to re-use the query execution plans.

bertolami