Announcement Announcement Module
Collapse
No announcement yet.
Multiple keys for @Cacheable Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Multiple keys for @Cacheable

    Is there a simple way how to use multiple arguments as keys for @Cacheable? For example, if I wanted to cache
    Code:
    @Cacheable(value="book", key="???")
    public Book findBook(String author, String title,
                         boolean checkWarehouse, boolean includeUsed)
    with key determined by both author and title.

    I tried asking that on SO but without success.

    Proposal: What about changing Cacheable's String key to String[] keys in a future version? I suppose the internal implementation could be easily modified to take care of that.

  • #2
    Have you read the (java)docs for @Cacheable? key is an expression (SpEL) so you can basically select what you want/use as a key by writing the correct expression...

    Comment


    • #3
      Originally posted by Marten Deinum View Post
      Have you read the (java)docs for @Cacheable? key is an expression (SpEL) so you can basically select what you want/use as a key by writing the correct expression...
      Of course I did. I managed to solve it by writing expressions like author.hashCode() + 31 * title.hashCode() or separating it into a helper function
      Code:
      public static int hashes(Object... args) {
          return java.util.Arrays(args).asList().hashCode();
      }
      and calling it like key="T(mypackage.MyHelperClass).hashes(author, title)".

      Thinking about it, maybe a better solution would be to use a list instead of working with hash codes (I'd have to check if it works):
      Code:
      public static int list(Object... args) {
          return java.util.Arrays(args).asList();
      }
      and calling it like key="T(mypackage.MyHelperClass).list(author, title)".

      But all this is very far from elegant and readable. The simple fact that I want to use two fields as the key is buried under a lot of boilerplate code. Is there a simpler solution I'm missing?

      Thanks,
      Petr

      Comment

      Working...
      X