Results 1 to 3 of 3

Thread: Multiple keys for @Cacheable

  1. #1
    Join Date
    Apr 2010
    Location
    Czech Republic
    Posts
    14

    Question 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. #2
    Join Date
    Jun 2006
    Location
    The Netherlands
    Posts
    13,695

    Default

    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...
    Marten Deinum
    Java Consultant / Pragmatist / Open Source Enthousiast / Author


    Pro Spring MVC: With Web Flow
    Conspect

    Have you read the reference guide.
    Use the [ code ] tags, young padawan

  3. #3
    Join Date
    Apr 2010
    Location
    Czech Republic
    Posts
    14

    Default

    Quote 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

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •