Hibernate / MyBatis Interview questions
How does MyBatis's second-level cache work?
The second-level cache is an optional, mapper-scoped (namespace-scoped) cache that persists across sessions, storing query results so that different SqlSession instances executing the same query against the same mapper can share cached results rather than each hitting the database independently.
<mapper namespace="com.example.mapper.UserMapper"> <cache eviction="LRU" flushInterval="60000" size="512" readOnly="true"/> <!-- statements --> </mapper>
Unlike the first-level cache, the second-level cache must be explicitly enabled — both globally (via cacheEnabled in mybatis-config.xml) and per mapper (via the <cache/> element shown above) — and it's configurable with settings like eviction policy, flush interval, maximum size, and whether cached objects are read-only or should be safely copied on each retrieval.
Because the second-level cache can serve stale data if used carelessly — especially in applications with multiple mappers or external processes modifying the same underlying tables — it needs to be applied thoughtfully: entities that change frequently, or that are modified outside the mapper's own insert/update/delete statements, are poor candidates, while relatively static, read-heavy reference data (like a list of countries or categories) is a much safer fit.
More Related questions...