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.
Here is the query:
select count(*) from R r where r.ISREPLACEDBY = 0
and r.STATUS='OK' and r.A = ?
and r.C in
(select distinct RC from CX cx where cx.FROMDATE >= ? and cx.FROMDATE <=?)
For complex queries, HQL is much more legible than Criteria.
In Hibernate, the Criteria API helps us build criteria query objects dynamically. Criteria is a another technique of data retrieval apart from HQL and native SQL queries. The primary advantage of the Criteria API is that it is intuitively designed to manipulate data without using any hard-coded SQL statements.
HQL is suitable for executing Static Queries, where as Criteria is suitable for executing Dynamic Queries. HQL is to perform both select and non-select operations on the data, Criteria is only for selecting the data, we cannot perform non-select operations using criteria.
Hibernate provides alternate ways of manipulating objects and in turn data available in RDBMS tables. One of the methods is Criteria API, which allows you to build up a criteria query object programmatically where you can apply filtration rules and logical conditions.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With