MyBatis implements its second-level cache using the Decorator pattern to allow flexible caching strategies. The architecture consists of:
- Cache Interface: The standard definition for cache operations (
putObject, getObject, removeObject, clear, getSize). - PerpetualCache: The base implementation using a
HashMap to store data, where the key is a CacheKey and the value is the cached object. - Decorators: Specialized implementations in the
decorators package (e.g., ScheduledCache, LruCache) that wrap the base cache to add features like time-based expiration or size limits.
public interface Cache {
String getId();
void putObject(Object key, Object value);
Object getObject(Object key);
Object removeObject(Object key);
void clear();
int getSize();
default ReadWriteLock getReadWriteLock() { return null; }
}