Adopt-a-JSR / jcache-javaee

JCache JSR-107 Integration for Java EE 8
Apache License 2.0
7 stars 1 forks source link

Align programmatic and annotation cache API #4

Open OndroMih opened 8 years ago

OndroMih commented 8 years ago

The default cache key for annotation API is not defined. The JCache JSR 107 only provides a way to generate the key of type GeneratedCacheKey, which implies that the default cache key must also implement that interface.

It is not easy to access a cache defined by annotations on methods with the programmatic API, as the default class of the key is unknown. It would help if it was possible to acquire a default instance of GeneratedCacheKey for varargs params matching the arguments to annotated methods.

The following does not work:

@Stateless
public class AnEJB {
  @CacheResult
  public String getResult(String key) { ... }
}
...
String valueViaAnnotation = anEJB.getResult(key);
String valueViaAPI = cache.get(key);
assertNotNull(valueViaAPI);   
/* fails because the value is not stored under key, but under an instance of GeneratedCacheKey generated from key */

The following might work to get the value from cache programmatically, with defining a custom CacheKey generator:

String valueViaAnnotation = anEJB.getResult( key );
GeneratedCacheKey cacheKey = cacheService.getDefaultCacheKey( key );
String valueViaAPI = cache.get( cacheKey);
assertNotNull(valueViaAPI);   
/* assertion passes, as the cacheService provides the same key as is generated during execution of anEJB.getResult( key ); */
eolivelli commented 8 years ago

I have already worked on something similar. Here is the list of common issues during automatic key generation: 1) support of non key arguments Sometimes there are arguments which must not be taken into account while creatingthe key. Annotations on parameters will be useful 2) support of parameters values trasformations. For instance string parameters which must be considered case insensitive/transformed tolowercase form. Even in this case annotations on parameters will be useful

jerrinot commented 8 years ago

@OndrejM: what type is cacheService?

@eolivelli: I really like the idea of annotations on parameters to select arguments for key generation Implementing a new CacheKeyGenerator just to select the right arguments for key generation sounds like an overkill.

I also wonder why the spec forces all keys to implement theGeneratedCacheKey interface. Why it can't just require keys to be Serializable (and even this is questionable - the imperative API does not require it). + perhaps describe expected properties of the equals/hashcode methods?

chrisknoll commented 7 years ago

The spec should follow the same pattern as the HashMap<K,V>, where you can specify the types of Keys in the map, but the get() signature is get(Object k) because when finding V, you only care that k.hash and k.equals matches the key in the map. The type doesn't matter.