The first-level cache is the persistence context’s session-scoped store of managed entity instances. During one unit of work, Hibernate checks this cache before querying the database by identifier. A cached entity therefore avoids another database hit, and repeated lookups with the same persistence context return the same entity instance. section 10.1.2
The cache affects persistence operations in several important ways:
- Keeps one managed representation of an entity for a given identifier within the persistence context, supporting consistent object identity and avoiding conflicting representations in an object graph. section 10.1.2
- Resolves entities returned by arbitrary queries against already-managed instances before reading the remaining result-set data. section 10.1.2
- Ignores potentially newer query-result data when the same identifier is already managed, consistent with read-committed database isolation. section 10.1.2
- Remains enabled for the persistence context and cannot be turned off; its contents participate in dirty checking and eventual synchronization with the database. section 10.1.2
Repeated lookup in one unit of work
Given a persistence context em, the first call to em.find(Item.class, ITEM_ID) may load the item from the database. A consecutive call with the same entity type, identifier, and persistence context returns the managed instance from the first-level cache without another database hit. A different persistence context has its own cache. section 10.1.2
The cache is part of the persistence context rather than an independent shared cache. Its scope follows the unit of work, while transaction boundaries and concurrency controls provide broader guarantees through database isolation, versioning, or locking. section 10.1.2 section 11.5
