Search code examples
hibernatejpaeclipselinkhqljpql

The difference between select * where id = :id and entity manager find()


I know that both

EntityManager.createQuery("select e from Entity e where e.id = :id")

and:

EntityManager.find(Entity.class,id)

returns the same result but, I really want to know the difference between them.


Solution

  • They produce the same SQL too.

    There was a discussion about the possibility to generate different SQL in some cases, but nothing different was found.

    The differences stay in how they can help you in different cases, but only at the code level:

    • The createQuery requires a JPQL/HQL to work. Any change on the id column name or entity name will affect the query string. The find method not suffer of the same problem.
    • You need more boilerplate code to work with createQuery (Query class, call setParameter method, query String, etc).