5

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.

1
  • 2
    em.find() won't execute any query if the entity has been loaded in the first-level cache already.
    – JB Nizet
    Apr 8, 2018 at 7:12

1 Answer 1

3

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).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.