Search code examples
hibernatejpahql

When to use HQL over Hibernate OO approach?


I am learning hibernate and reading online material to know about this.

When is it preferred to use HQL (or SQL) over the OO way which hibernate provides? That is, when should One prefer HQL over , say, session.get()? (read operation)

Can anyone help me understand this?


Solution

  • Even if Hibernate is the most commonly JPA implementation used, I would stick rather on the specification API (JPA).
    So EntityManager rather than Session.

    Generally you want to write your own queries as queries have a minimal level of complexity.
    But specific JPA/Hibernate methods don't allow to perform this kind of queries.
    These methods handle only simple cases.

    So as a general rule, you should favor specific JPA/Hibernate methods over custom query creating at each time you may.
    It is often a shortcut to avoid writing boiler plate code with JPQL.
    For example if you want to retrieve a entity from its ID, you don't have any value to write at hand a so simple query.
    You will have to write boiler plate code (creating query, setting parameter query, executing query).
    Using EntityManager.find(Class<T>, Object) is a much simpler and also clearer approach as you don't need to go further to understand the behavior.

    Note that Spring Data JPA goes still further by providing more methods to handle other classic queries.
    The SimpleJpaRepository class is a good example.

    At last, note that in some cases, specific JPA/Hibernate methods to manipulate entities are not a choice.
    The operations related to the entities or the EntityManager state can be performed only with these methods (persist(), flush() or refresh(), clear(), ...).