Ehcache is a very robust in-memory cache. In production, Ehcache could be better solution for Mybatis cache (More on Mybatis internal cache)
How to use Ehcache as Mybatis cache (2nd level cache)
You can set Mybatis 2nd level cache (Global cache) as 3rd party. (You can not change local session cache type)
- Import required library (mybatis-ehcache, ehcache)
- (Optional) Generate ehcache config (ehcache.xml)
- Declare 3rd party cache inside mybatis mapper xml
1. Import required library
To use Ehcache, mybatis-ehcache and ehcache library must be imported.
mybatis-ehcache library is the bridge between Ehcache and Mybatis.
As of this writing, mybatis-ehcache is version 1.1 and is dependent on Ehcache 2.6.x. Therefore you must import ehcache 2.6.x (Ehcache package structure has changed from 3.x)
2. Ehcache config xml (Optional)
mybatis-ehcache library uses ehcache.xml in the root classpath. (You can not customize the path or file name) If the file is not found, default config is applied. The following is a sample ehcache.xml
You can refer full options at ehcache document. ehcache.xml schema also has changed from 3.x
3. Declare Ehcache inside mybatis mapper xml
Inside mapper xml, declaration of cache tag enables to use 3rd party cache. Check the following sample
To enable Ehcache, declare “org.mybatis.caches.ehcache.EhcacheCache” as the type of the cache.
(Important!) Consideration for detailed configuration
The beauty of Ehcache comes from its detailed configuration, which is defined at ehcache.xml. The most import point is that cache name must be equal to mapper’s namespace. If no matching cache name is found at ehcache.xml, CacheManager.addCache(namespace) is called internally, which causes a new cache to be generated with default options, which you might not want. Notice that above sample ehcache.xml declares “test.TestMapper”, which is same with mapper’s namespace