liveBook · Manning

Find

As explained in Java Persistence with Spring Data and Hibernate epub

find is a JPA EntityManager operation that retrieves an entity by its type and identifier, returning null when no matching entity exists.

EntityManager.find() retrieves an entity by its type and identifier. The returned entity is persistent in the current unit of work; if no matching entity exists, the method returns null. section 10.2.3

A lookup has several persistence-context implications:

  • If the entity is not already in the persistence context, the lookup hits the database. A repeated lookup can return the same cached instance. section 10.2.3 section 10.1.1
  • The entity is initialized during loading. Changes made while it is persistent are detected and synchronized with the database when the persistence context flushes at commit. section 10.2.3
  • After the unit of work ends and the persistence context closes, the retained entity reference is detached; merge() can save later modifications in a new unit of work. section 10.1.1

Retrieve and modify an Item

Item item = em.find(Item.class, ITEM_ID); if (item != null) { item.setName("New Name"); } section 10.2.3

Path: managing-data/src/test/java/com/manning/javapersistence/ch10
 /SimpleTransitionsTest.java – retrievePersistent()
 
Item item = em.find(Item.class, ITEM_ID);    #1
if (item != null)
    item.setName("New Name");                #2
#1 The instruction will hit the database if <kbd>item</kbd> is not already in the persistence context.
#2 Then we modify the name.

Shows a find() lookup followed by a guarded Item update. section 10.2.3

How Java Persistence with Spring Data and Hibernate epub covers it

How deep it goes
Traces lookup through caching, entity initialization, change detection, and commit-time synchronization.
Examples
Demonstrates retrieving an Item by ITEM_ID, changing its name, and repeating a lookup for the same instance.
What it assumes
Assumes a known entity identifier and a unit of work; does not explain how to obtain the identifier.
What you can do after
Apply EntityManager.find() to retrieve an Item, modify it within a unit of work, and rely on detected changes being synchronized at commit.
How it connects
Connects EntityManager lookup to persistence contexts, detached entities, merge, and Hibernate flushing.

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.