Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 625
Andriel Avatar asked Mar 29 '13 14:03

Andriel


People also ask

Which method of the JPA EntityManager would you use?

In JPA, the EntityManager interface is used to allow applications to manage and search for entities in the relational database. The EntityManager is an API that manages the lifecycle of entity instances. An EntityManager object manages a set of entities that are defined by a persistence unit.

Which method of the JPA EntityManager would you use to force synchronizing?

To force synchronization of the managed entity to the data store, invoke the flush method of the EntityManager instance.

What is the method on the EntityManager which is used to update entities in the underlying database?

getTransaction() method - This method returns the resource-level EntityTransaction object.


2 Answers

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.

like image 138
Nathan Hughes Avatar answered Oct 19 '22 08:10

Nathan Hughes


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.

like image 32
Kevin Bowersox Avatar answered Oct 19 '22 08:10

Kevin Bowersox