7. Session cache - L1
● Enabled by default
● Used transparently during the session
● All objects that was saved or retrieved
○ save
○ update
○ get
○ list
○ iterate
● flush() - will sync cache to DB
● clear() - will evict all objects
8. L2 cache - configuration
1. Get ehcache.jar and add it to classpath
2.
3. Edit persistence.xml
9. L2 Cache
● Inter-session cache
● Can be clustered
● Configurable with XML or Annotations
● Divided to regions
○ Entity - data
○ Collections - relations
○ Queries - query results
○ Timestamps - last update timestamp for tables
10. L2 cache strategies
● Read-only
○ simplest, safest and fastest
○ supports insert, no update/delete
○
● Nonstrict Read-Write
○ occasional writes, no locking cache
○ low prob. that 2 transactions will write the same
object
○ async - update
11. L2 cache strategies
● Read-Write
○ read committed - transaction isolation
○ uses soft locks
○ async - cache update out of tx
● Transactional
○ only with JTA (i.e. with distributed tx support)
○ serialized transaction isolation
○ sync - cache update inside tx
12. L2 cache - how it works
● Does not cache actual objects
● Caches values of the properties
● Mappings (relations) are not cached by
default
○ it can helps with N+1 queries
13. Example
● cache of the mapping is optional
● although it's the best place to improve
● beware of code altering the associations
and not cascading the change
17. Query cache
What happens if don't query by Id ?
The query cache will look like:
*---------------------------------------------------------
-*
| Query Cache
|
|---------------------------------------------------------
-|
| ["from Person as p |
18. Query cache
There are 3 cache regions:
● StandardQueryCache
○ cached query results
● UpdateTimestampsCache
○ holding timestamps of the most recent updates
● NamedQueryCaches
○ Query.setCacheRegion(name)
19. Query Cache
QC is useful when you query by "Natural id"
Criteria crit = session.createCriteria(Person.class);
crit.add(
Restrictions.
naturalId().
set("email", "joey@ramones.com")).
setCacheable(true).
uniqueResult();
Since Natural Id immutable, Natural Id -> Primary Key
mapping cannot be invalidated
This allows Hibernate to bypass UpdateTimestampCache
20. Query Cache - Pitfalls
● Any update to the underlying table updates the
timestamp cache - invalidates all entities
● Memory
○ the queries are large pretty strings and the
bind variables can be objects
● Lock contention - QC has a coarse lock on
timestamp cache for insert/update/delete and
lookups
21. Stuff to remember
● Cache cannot know about updates made to
the persistent store by another application
● Query cache - unless you use a natural key
is almost always a bad idea
○ unless you know what you're turning it on
○ you can show an improvement with realistic load
● TTL and TTI
○ tune them