What is Entity Manager?

Asked

Viewed 2,391 times

4

What is the Java Entity Manager?

Attending a class on java the teacher mentioned that the method find() of Entity manager and that this method, when searching for a record in the database stores the object in an area where it becomes "monitored" and serves as primary cache.

My question is what would this Entity manager be? What is it used for? And what area is this?

  • https://docs.oracle.com/javaee/7/api/javax/persistence/EntityManager.html

  • 1

    Ah, just so we’re clear, I’m not the one who denied you.

  • 1

    For me it is a valid doubt, I did not understand the downvote.

1 answer

7


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:

  1. 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.
        }
    }
    
  2. 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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.