Differences between Criteria and HQL

Asked

Viewed 588 times

5

In the booklets I read and tutorials I accompanied the Criteria is more used, but I identified more with HQL. But I have the following doubt, all that is done with Criteria it is possible to do with HQL?

Example HQL:

//Select * from Suspensao
@NamedQueries({
    @NamedQuery(name = "Suspensao.listar", query = "SELECT suspensao FROM Suspensao suspensao") })

And then on the DAO:

Query consulta = sessao.getNamedQuery("Suspensao.listar");
            lista = consulta.list();

1 answer

3


With rare exceptions, everything you do with one can also do with the other. I think the difference lies in how each one works. Some interesting details to take into consideration at the time of your choice:

  • Criteria is the best choice for dynamic queries, when you deal with many optional parameters, which usually happens on any web system. It is much easier to dynamically sort or add/remove a restriction based on a parameter. Paging with Criteria is also much easier.

  • HQL is more interesting for static queries. HQL tends to generate smaller, clearer and easier to understand code. In addition you can turn these hql queries into named queries, which brings a certain performance gain.

I believe that choosing to use only one of them is to give up an interesting part of the tools that Hibernate offers. Consider using both, each for the type of research you’re currently mounting.

  • Got it, thank you very much for the explanation

Browser other questions tagged

You are not signed in. Login or sign up in order to post.