Mybatis Cache
Mybatis Cache
Note : For spring and mybatis integration, mybatis session is tied to spring transaction
Second Level Cache
- Cached object has to be implemented Serializable
- add
<cache />
in sql xml file - session2 only can get cached object after session1 close or commit
<select>
,<insert>
,<update>
and<delete>
haveflushCache
attribute to clear cache after execute this statement.<select>
hasuseCache="false"
to desiable cache this select result- By default,
<insert>
,<update>
and<delete>
of same namespace will clear 2nd cache, developer can useflushCach="true"
to disable this feature - Use LRU(Least Recently Used) to clear 2nd cache
<cache readOnly="true" />
means return reference of cached object to caller, whilefalse
means return copy instance of cached object, defaulst is false.<cache-ref namespace="..." />
share 2nd cache config/instance
Custom Cache
- Implements
Cache
intertace <cache type="XX.CustomCache"><property name="cacheFile" value="..." /></cache>
- eviction strategy, readOnly etc are not applicable for custom cache
Mybatis and Ehcache Integration
- add
mybatis-ehcache.jar
andehcache.jar
- add ehcache xml file
<cache type="...ehcache.."/>
Note : mybatis-ehcache-1.1.0 not support ehcache 3.X
2nd Cache Risk
Second level cache has risk at multiple tables query, please refer to this and this in Chinese.
Even developer can use <cach-ref />
to avoid this risk, but 2nd level cache become more meaningless in this case because operation of multiple namespace will affect cache.
Therefore, it is a good practice to use cache in business service layer without mybatise cache.
Written on March 25, 2018