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
