8

I would like to know the difference between on these methods.

When use the createQuery()and find() methods of EntityManager ?

What the advantages about each of them ?

Thank you for answer me.

2
  • 2
    Have you read the Javadoc? Commented Mar 29, 2013 at 14:13
  • 1
    @Zutty Yes, I have, but I didn't understand very well. Commented Mar 29, 2013 at 14:30

2 Answers 2

14

You use find when you want to look up an entity by primary key. That means you know exactly what you're looking for, you just want to pull it out of the database.

You use createQuery when you want to find entities using criteria or if you want to use a JPQL statement to define what you get back. So you would use the query when you want to get an entity or collection of entities matching some conditions.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you to reply. Then the advantages is the same for both. So depends what I'll search exactly. Nice post link's. :-)
Correct me if I am wrong, but .find() hits 2nd level cache, whereas createQuery will not
@Broccoli: createQuery uses the query cache, see vladmihalcea.com/how-does-hibernate-query-cache-work
11

The createQuery method allows you to create a JPQL statement that will be executed. The JPQL statement allowed is much more dynamic than the one executed by find. For example given the following table:

create table CAT(
   cat_id integer,
   cat_name varchar(40)
)

You could execute a query to find the cat by name.

entityManager.createQuery("select c from Cat c where c.name = :name");

The find method only allows you to retreive an object using its primary key. So to use the find method for the above table:

entityManager.find(Cat.class, new Integer(1));

In a nutshell, createQuery allows you to retrieve entities in a more dynamic fashion, while find limits you to searching for an entity with a known id.

2 Comments

@Andriel Glad I could help do you have any lingering questions?
At moment its all ok! Thank you !! :-)

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.