What are the pros and cons of using Criteria or HQL? The Criteria API is a nice object-oriented way to express queries in Hibernate, but sometimes Criteria Queries are more difficult to understand/build than HQL.
When do you use Criteria and when HQL? What do you prefer in which use cases? Or is it just a matter of taste?
Answer:
I'm the guy who wrote the Hibernate 3 query translator back in 2004, so I know something about how it works.
Criteria, in theory should have less overhead than an HQL query (except for named queries, which I'll get to). This is because Criteria doesn't need to parse anything. HQL queries are parsed with an ANTLR-based parser and then the resulting AST is turned into SQL. However, with HQL/JPAQL you can define named queries, where the SQL is generated when the SessionFactory starts up. In theory, named queries have less overhead than Criteria.
So, in terms of SQL-generation overhead we have:
- Named HQL/JPAQL Query - SQL generation happens only once.
- Criteria - No need to parse before generating.
- (non-named) HQL/JPAQL Query - Parse, then generate.
That said, choosing a query technique based on the overhead of parsing and SQL generation is probably a mistake in my opinion. This overhead is typically very small when compared to performing a real query on a real database server with real data. If this overhead does actually show up when profiling the app then maybe you should switch to a named query.
Here are the things I consider when deciding between Criteria and HQL/JPAQL:
- First, you have to decide if you're OK with having a dependency on Hibernate-proprietary API in your code. JPA doesn't have Criteria.
- Criteria is really good at handling many optional search parameters such as you might find on a typical web page with a multi-parameter 'search form'. With HQL, developers tend to tack on where clause expressions with StringBuilder (avoid this!). With Criteria, you don't need to do that. Hardik posted similar opinions.
- HQL/JPAQL can be used for most other things, because the code tends to be smaller and easier for developers to understand.
- Really frequent queries can be turned into named queries if you use HQL. I prefer to do this later, after some profiling.
I mostly prefer Criteria Queries for dynamic queries. For example it is much easier to add some ordering dynamically or leave some parts (e.g. restrictions) out depending on some parameter.
On the other hand I'm using HQL for static and complex queries, because it's much easier to understand/read HQL. Also, HQL is a bit more powerful, I think, e.g. for different join types.