Hibernate / MyBatis Interview questions
What is the difference between first-level and second-level cache?
Both caches avoid redundant database queries, but they differ substantially in scope, default status, and the kind of staleness risk they carry.
| First-Level Cache | Second-Level Cache |
| Scoped to a single SqlSession. | Scoped to a mapper namespace, shared across sessions. |
| Enabled by default, cannot be turned off. | Disabled by default; must be explicitly enabled. |
| Cleared automatically on commit/rollback/close. | Persists across sessions until explicitly flushed or evicted. |
| Low staleness risk, given its short-lived scope. | Higher staleness risk if misapplied to frequently-changing data. |
The practical implication is that the first-level cache can be relied on essentially without thought — it's automatic and safely scoped — while the second-level cache is a deliberate performance optimization that requires understanding a specific mapper's data access patterns well enough to judge whether cross-session caching is actually safe for that particular data, rather than something to enable indiscriminately across every mapper.
More Related questions...