Using Ehcache instead of Mybatis internal cache

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)

  1. Import required library (mybatis-ehcache, ehcache)
  2. (Optional) Generate ehcache config (ehcache.xml)
  3. 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

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

mapper.xml.with.ehcache

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

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.