liveBook · Manning

EntityManager

As explained in Java Persistence with Spring Data and Hibernate epub

EntityManager is the JPA API interface for managing the lifecycle and persistence operations of entity instances.

EntityManager is the main Jakarta Persistence API for a unit of work. It stores and loads entities, executes queries, and controls the persistence context that tracks entity instances. Hibernate implements this JPA interface; Spring Data JPA offers a repository-based alternative for common persistence operations. section 10.2 section 1.3 section 2.8

In a Java SE application, obtain an EntityManager from a shared EntityManagerFactory. Use it for one unit of work in one thread, begin a transaction, perform the work, and commit. Handle failures with rollback and exception handling; close the EntityManager in a finally block. Closing it ends the persistence context. section 10.2.1

Listing 10.1 A typical unit of work
Path: managing-data/src/test/java/com/manning/javapersistence/ch10
 /SimpleTransitionsTest.java
 
EntityManagerFactory emf =
        Persistence.createEntityManagerFactory("ch10");
 
// . . .
EntityManager em = emf.createEntityManager();
 
\1 {
    em.getTransaction().begin();
 
    // . . .
    em.getTransaction().commit();
} catch (Exception ex) {
    // Transaction rollback, exception handling
    // . . .
} finally {
    if (em != null && em.isOpen())
        em.close();
}

The unit-of-work listing shows factory creation, transaction boundaries, and cleanup. Its catch block is a placeholder: implement rollback and exception handling rather than leaving it empty. section 10.2.1

Find, change, and commit

Call em.find(Item.class, ITEM_ID), then, if it returns an Item, call item.setName("New Name"). The retrieved instance is persistent: Hibernate detects the change and issues the necessary SQL UPDATE when it flushes the persistence context. find() returns null when the identifier is absent. A second find() for the same type and identifier within the context returns the same cached Java instance. section 10.2.3

The persistence context determines when changes become database operations:

  • Creating an EntityManager does not itself require database access; Hibernate obtains a JDBC connection when SQL must run. section 10.2.1
  • Commit normally triggers dirty checking and synchronization. flush() forces synchronization during an active transaction. section 10.2.1 section 10.2.9
  • With the default FlushModeType.AUTO, Hibernate normally flushes changes before a query. FlushModeType.COMMIT postpones that flush, so a query may return data different from the in-memory entity state. section 10.2.9

EntityManager also supports operations across the transient, persistent, detached, and removed entity states. Its persistence context caches managed instances; detach() removes an individual instance from that context. For Hibernate-specific operations, unwrap() can expose a Session. In a Spring application, Spring can instead control the EntityManager and transaction manager. section 10.4 section 10.0 section 14.6

How Java Persistence with Spring Data and Hibernate epub covers it

How deep it goes
Works through transaction scope, entity retrieval and identity, dirty checking, and flush modes; defers detailed concurrency and exception handling.
Examples
Uses a Java transaction listing and an Item lookup whose changed name is synchronized on flush.
What it assumes
Assumes Java entities and basic persistence mapping; introduces the persistence lifecycle before EntityManager operations.
What you can do after
Operate/configure it to load and modify entities, delimit a unit of work, and control when changes flush.
How it connects
Links entity lifecycle states, persistence contexts, transactions, JPQL queries, Hibernate Session, and Spring Data JPA.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Java Persistence with Spring Data and Hibernate epub. The section links point to the parts of the book it draws on.