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:
Here are the things I consider when deciding between Criteria and HQL/JPAQL:
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.
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.
- 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.