2

I am setting up Hibernate Caching and want to cache certain entities in different regions. For example, some entities can be "stale" for up to 5 minutes, some for an hour, and some (like lookups) won't change for weeks. To facilitate easy config of regions in my code, I'm trying the following:

I created an annotation named @LookupCache (and @DailyCache etc)

@Cache(region = "lookups", usage = CacheConcurrencyStrategy.READ_ONLY)
@Retention(RetentionPolicy.RUNTIME)
public @interface LookupCache {}

And I am adding that annotation to my Hibernate/JPA entity:

@LookupCache
public class Course {}

This way, I can easily change the region or attributes of the @LookupCache without having to change the annotation params of every class.

However, the cache loader doesn't pick up this inherited @Cache notation. How do I get the @LookupCache annotation to inherit the annotations that are applied to it?

Update: To clarify, the @Cache annotation is a built-in hibernate annotation used by second-level caches like EHCache. I can't modify the @Cache annotation to make it inheritable by other annotations (my client doesn't want to maintain a special fork of hibernate). This is probably my only option though.

2
  • 2
    Annotations don't work like that, I'm afraid. There's no "inheritance" like what you're looking for, it's up to Hibernate to do that explicitly, which won't happen because it's a custom annotation. Commented Nov 25, 2009 at 17:15
  • So much for DRY. Thanks. Commented Nov 25, 2009 at 17:40

1 Answer 1

2

Here is a simple example that shows how to retrieve details of the @Cache annotation applied to your @LookupCache annotation:

Course c = new Course();
LookupCache lookupCache = c.getClass().getAnnotation(LookupCache.class);
Cache cache = lookupCache.annotationType().getAnnotation(Cache.class);
System.err.println("region " + cache.region());
System.err.println("usage " + cache.usage());

You just need to make sure that @Cache annotation also has @Retention(RetentionPolicy.RUNTIME)

Sign up to request clarification or add additional context in comments.

1 Comment

This is the receipe I was looking for reading annotations's annotations! Since the getClass().getAnnotations() was returning proxies!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.