In JPA, the EntityManager
is the class responsible for managing the life cycle of the entities.
This class is capable of:
Locate entities through the method find
(which locates them through its primary keys). For example, if Funcionario
is an entity class (annotated with @Entity
) and we want to get the Funcionario
of id = 123:
EntityManager em = ...;
Funcionario f1 = em.find(Funcionario.class, 123);
Run queries using JPQL or even native SQL. For example:
String jpql = "SELECT f FROM Funcionario f WHERE f.empresa = :emp";
EntityManager em = ...;
Empresa emp = ...;
List<Funcionario> funcionariosDaEmpresa = em
.createQuery(jpql, Funcionario.class)
.setParameter("emp", emp);
.getResultList();
Commit entities. For example:
EntityManager em = ...;
Funcionario f = new Funcionario();
f.setNome("João Silva");
em.persist(f);
Update entities in the database. For example:
EntityManager em = ...;
Funcionario f = em.find(Funcionario.class, 123);
f.setCorFavorita("Amarelo");
em.merge(f);
Update entities from the database. For example:
EntityManager em = ...;
Funcionario f = em.find(Funcionario.class, 123);
// ...
// ... Algum outro processo altera o estado do funcionário 123 aqui.
// ...
// Atualiza o estado da instância na memória de acordo com o que há no banco de dados.
em.refresh(f);
Remove entities from the database. For example:
EntityManager em = ...;
Funcionario f = em.find(Funcionario.class, 123);
em.remove(f);
An instance of a EntityManager
can be obtained in two ways:
Dependency injection (typical case used in Spring and Ejbs):
@Stateless
public class MeuBean {
@PersistenceContext(unit = "testePU")
EntityManager em;
public void meuMetodo() {
// Usa o em aqui.
}
}
Through the EntityManagerFactory
and class Persistence
:
EntityManagerFactory factory = Persistence.createEntityManagerFactory("testePU");
EntityManager entityManager = factory.createEntityManager();
The EntityManager
keeps the entities he manages in a state called Managed - these are the entities he monitors. These entities are the ones he creates through the method find
, by means of JPQL or received in the method persist
or merge
. It caches these entities so that reading twice the same database entity will not produce two different instances - the same instance is returned on second reading.
However, not all instances of entities are Managed - to know those that have just been instantiated and have not yet been passed on to EntityManager
(state new), those excluded by the method remove
(state re-moved) and those that have been disconnected from EntityManager
by means of methods clear()
or detach(Object)
(state Detached).
See more about JPA, including EntityManager
, at this link.
https://docs.oracle.com/javaee/7/api/javax/persistence/EntityManager.html
– Victor Stafusa
Ah, just so we’re clear, I’m not the one who denied you.
– Victor Stafusa
For me it is a valid doubt, I did not understand the downvote.
– user28595