I had configured Spring Boot + Ehcache3 to cache i18n messages pulled from the database and everything was working fine until I expanded and encountered null results from the database for some keys. Ehcache barfed with a ClassCaseException saying the default org.springframework.cache.support.NullValue
is not the expected com.example.Message
. After wrestling with this, I tried a dual cache arrangement. One the DAO impl:
@Caching(cacheable = {
@Cacheable(value = "messages", key = "#locale + ':' + #key", unless = "#result == null"),
@Cacheable(value = "nullMessages", key = "#locale + ':' + #key", unless = "#result != null")})
public Optional<Message> findByKeyAndLocale(String key, String locale) {
// fun with JDBC
}
and in the ehcache.xml
:
<cache alias="messages" uses-template="default" >
<key-type>java.lang.String</key-type>
<value-type>com.example.Message</value-type>
</cache>
<cache alias="nullMessages" uses-template="default" >
<key-type>java.lang.String</key-type>
<value-type>org.springframework.cache.support.NullValue</value-type>
</cache>
This seems to be working OK. My question here is: Is there a better way? The two caches are using the same key, but it looks like that key is potentially computed twice. Is there a way to improved that? Better yet, is there a magic incantation to enable ehcache3 to handle null result caching out-of-the-box?
-GBS