EntityManager.find() retrieves an entity by its class and identifier. It returns a managed, fully initialized instance when found, or null when no matching entity exists. section 10.2.3
Retrieve and modify an Item
Item item = em.find(Item.class, ITEM_ID); if (item != null) item.setName("New Name"); The first lookup queries the database when the persistence context lacks the entity. The returned Item is managed, so changes are detected and written as SQL UPDATE statements when the unit of work flushes during commit. section 10.2.3
Use find() with these lifecycle and caching expectations:
- A missing entity produces null; code should test the result before modifying it. section 10.2.3
- After the persistence context closes, the loaded instance becomes detached; later changes require merge() in a new unit of work. section 10.1.1
- Hibernate normally queries the database on a cache miss, although an optional second-level cache can avoid that query. section 10.2.3
