Differences between Criteria and HQL

5

In the handouts I read and tutorials I followed Criteria is more used, however I identified myself more with HQL . But I have the following doubt, everything done with Criteria can do with HQL ?

HQL example:

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

Then on DAO:

Query consulta = sessao.getNamedQuery("Suspensao.listar");
            lista = consulta.list();
    
asked by anonymous 04.08.2015 / 17:02

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 handle many optional parameters, which usually happens on any web system. It is much easier to dynamically sort or add / remove a constraint based on a parameter. Pageing with Criteria is also much easier.

  • HQL is more interesting for static queries. HQL tends to generate a 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 think choosing to use just one of them is giving up an interesting part of the tools that Hibernate offers you. Consider using both, each for the type of search you are currently mounting.

    
04.08.2015 / 22:44