From the spring documentation :
@Cacheable(value="bookCache", key="isbn")
public Book findBook(ISBN isbn, boolean checkWarehouse, boolean includeUsed)
How can I specify @Cachable to use isbn and checkWarehouse as key?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Update: Current Spring cache implementation uses all method parameters as the cache key if not specified otherwise. If you want to use selected keys, refer to Arjan’s answer which uses SpEL list
{#isbn, #includeUsed}which is the simplest way to create unique keys.From Spring Documentation
Before Spring 4.0
I suggest you to concat the values of the parameters in Spel expression with something like
key="#checkWarehouse.toString() + #isbn.toString()"), I believe this should work as org.springframework.cache.interceptor.ExpressionEvaluator returns Object, which is later used as the key so you don’t have to provide anintin your SPEL expression.As for the hash code with a high collision probability – you can’t use it as the key.
Someone in this thread has suggested to use
T(java.util.Objects).hash(#p0,#p1, #p2)but it WILL NOT WORK and this approach is easy to break, for example I’ve used the data from SPR-9377 :Both lines print -636517714 on my environment.
P.S. Actually in the reference documentation we have
I think that this example is WRONG and misleading and should be removed from the documentation, as the keys should be unique.
P.P.S. also see https://jira.springsource.org/browse/SPR-9036 for some interesting ideas regarding the default key generation.
I’d like to add for the sake of correctness and as an entertaining mathematical/computer science fact that unlike built-in hash, using a secure cryptographic hash function like MD5 or SHA256, due to the properties of such function IS absolutely possible for this task, but to compute it every time may be too expensive, checkout for example Dan Boneh cryptography course to learn more.