I was working with spring-ehcache-annotations and came across following scenario:
I have a simple POJO as follows
class Person{
private Long id;
private String name
//some code
}
Now in DAO I have
public Person getPerson(Long personId){}
public Person UpdatePerson(Person person){}
Now in update person I need parameter of class Person and I need to use personId of person as the key to cache.
This can be achieved by implmenenting CacheKeyGenerator for each class or putting blocks of if/e开发者_开发百科lse but can we have some configurable thing to give field of parameter to take as key ?
Can you switch to Spring 3.1 cache abstraction?
Your use case is then easily solvable by:
@Cacheable(key="#person.personId")
annotation.
This can all be done with annotations.
If the updatePerson
method takes a modified Person
that you are persisting, then you need to annotate the update method with TriggersRemove
to evict the updated Person from the cache. Then you need to rerun the getPerson
method to cache the updated Person.
See example code on the site: https://code.google.com/p/ehcache-spring-annotations/source/browse/examples/ehcache-spring-example-1/trunk/src/main/java/com/googlecode/ehcache/annotations/examples/impl/SpringJdbcWeatherServiceImpl.java
Based on the updateWeather
method in the link above, if I understand the issue at hand, you would do something like the following:
@Cacheable(cacheName="personCache", keyGenerator=@KeyGenerator(
name="ListCacheKeyGenerator",properties=@Property(name="includeMethod",value="false")))
public Weather getPerson(Long personId) {
return (Person)(getSession().get(Person.class, personId));
}
@TriggersRemove(cacheName="personCache", keyGenerator=@KeyGenerator(
name="ListCacheKeyGenerator",properties=@Property(name="includeMethod",value="false")))
public Weather updatePerson(@PartialCacheKey Long personId, Person person) {
getSession().merge(person);
return getPerson(personId);
}
Try adding @PartialCacheKey to the personId parameter of getPerson method.
Just like this:
@Cacheable(cacheName="personCache", keyGenerator=@KeyGenerator(
name="ListCacheKeyGenerator",properties=@Property(name="includeMethod",value="false")))
public Weather getPerson(@PartialCacheKey Long personId) {
return (Person)(getSession().get(Person.class, personId));
}
@TriggersRemove(cacheName="personCache", keyGenerator=@KeyGenerator(
name="ListCacheKeyGenerator",properties=@Property(name="includeMethod",value="false")))
public Weather updatePerson(@PartialCacheKey Long personId, Person person) {
getSession().merge(person);
return getPerson(personId);
}
精彩评论