✅ Short Answer
- READ_ONLY strategy: for immutable data — assumes entities never change → highest performance but unsafe if data is updated.
- READ_WRITE strategy: for mutable data — safely tracks changes and synchronizes the cache when entities are updated → ensures consistency at the cost of more overhead.
🔎 Detailed Explanation
🔹 READ_ONLY Strategy
✅ Designed for immutable entities → data that never changes after being saved (e.g., country codes, tax rates).
✅ Hibernate doesn’t track updates → no cache invalidation or synchronization needed.
✅ Fastest and simplest strategy → minimal overhead.
❌ Dangerous if data changes: updates bypass cache → causes stale data and inconsistency.
Use case example: Reference tables like Currency
, Country
, ProductCategory
.
🔹 READ_WRITE Strategy
✅ Designed for mutable entities → safe for data that can be updated.
✅ Hibernate manages cache synchronization:
- When an entity is updated, Hibernate updates or invalidates the cache entry to keep it consistent with the database.
✅ Slightly slower than READ_ONLY due to synchronization overhead.
✅ Prevents stale data scenarios when entities are modified.
Use case example: Entities like UserProfile
, Order
, or Product
with frequent reads + occasional updates.
📊 Quick Comparison Table
Feature | READ_ONLY | READ_WRITE |
---|---|---|
Suitable for | Immutable data | Mutable data |
Performance | Fastest | Slower (manages consistency) |
Cache consistency | No synchronization (risky if data changes) | Updates/invalidation on entity change |
Risk of stale data | High if data is updated | Low |
💡 Important Note
✅ If you mistakenly use READ_ONLY on mutable data, you’ll likely serve stale data → can cause subtle, critical bugs.
✅ READ_WRITE uses Hibernate’s transactional cache → ensures data consistency between DB and cache.
📌 Key Takeaways
✅ READ_ONLY → use only for truly immutable entities → offers best performance.
✅ READ_WRITE → use for entities that might change → safely updates or invalidates the cache to keep data consistent.