title: Spring Cache Abstraction: How to Deal With java.util.Optional<T>
body: <p>We have a lot of code in our code base that's similar to the following interface:</p>
  
  <pre><code>public interface SomethingService {
      @Cacheable(value = "singleSomething")
      Optional&lt;Something&gt; fetchSingle(int somethingId);
  
      // more methods...
  }
  </code></pre>
  
  <p>This works fine as long we're only using local caches. But as soon as we're using a distributed cache like Hazelcast, things start to break because <code>java.util.Optional&lt;T&gt;</code> is not serializable and thus cannot be cached.</p>
  
  <p>With what I've come up so far to solve this problem:</p>
  
  <ol>
  <li>Removing <code>java.util.Optional&lt;T&gt;</code> from the method definitions and instead checking for the trusty <code>null</code>.</li>
  <li>Unwrapping <code>java.util.Optional&lt;T&gt;</code> before caching the actual value.</li>
  </ol>
  
  <p>I want to avoid (1) because it would involve a lot of refactoring. And I have no idea how to accomplish (2) without implementing my own <code>org.springframework.cache.Cache</code>.</p>
  
  <p>What other options do I have? I would prefer a generic (Spring) solution that would work with most distributed caches (Hazelcast, Infinispan, ...) but I would accept a Hazelcast-only option too.</p>