JPA and Hibernate · senior
Optimistic locking and Hibernate caches
A @Version column stops lost updates. The second-level cache is per JVM unless clustered. For stock, use one atomic UPDATE.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- Lost update: two admins save the same product, the last save wins and one change disappears without an error.
@Version long versionmakes Hibernate addwhere id=? and version=?and bump the version. If 0 rows change, it throwsOptimisticLockException.- The version must go to the client and come back (in the DTO, or as
ETagandIf-Match) and be compared on the server. Otherwise the check does nothing. - Retry automatically only for changes that can be re-applied (a computed increment), never for a person's edit.
- Pessimistic:
@Lock(PESSIMISTIC_WRITE)(SELECT ... FOR UPDATE) inside a transaction, with a lock timeout, for hot rows. - For stock decrements use one atomic statement:
update product set stock = stock - :q where id = :id and stock >= :q, and check the row count. - First-level cache: the persistence context. Always on. The same id twice in a transaction means one SELECT.
- Second-level cache: shared across sessions in one JVM, through a provider (JCache, Ehcache, Caffeine). With six pods and local caches, each pod has its own copy and others stay stale until expiry. Good fit for the second level: read-mostly reference data. Spring's
@Cacheablewith Redis is shared by all pods and often simpler for API results.
The red pen
Common traps: mistake → fix
Mistake: Last save wins is acceptable
Fix: it silently loses a person's work.
Mistake: Second-level cache is shared between pods
Fix: not with a local provider.
Mistake: A version column works without the client sending it back
Fix: the server must compare the client's version.
Easy to hard
Questions interviewers ask, easy to hard
- Two admins edit the same product. What ends up in the database? How do you make the second save fail?
- Optimistic or pessimistic locking?
- What is the first-level cache? The second-level?
- Would you enable the second-level cache for six pods?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.