Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@Caching With Multiple Keys

I have a service that takes in a DTO and returns some result:

@Override
public int foo(Bar bar) {
    ....
}

Bar is as follows (simplified):

public class Bar {
    public int id;
    public String name;
    public String baz;

    @Override
    public int hashCode() {
        //this is already being defined for something else
        ...
    }

    @Override
    public boolean equals(Object o) {
        //this is already being defined for something else
        ...
    }
}

I want to use @Cacheable on the foo method; however, I want to hash on the id and name properties, but not baz. Is there a way to do this?

like image 659
Alex Beardsley Avatar asked Nov 14 '12 15:11

Alex Beardsley


2 Answers

You can use this approach also

@Override
@Cacheable(key="{#bar.name, #bar.id}")
public int foo(Bar bar) {
    ....
}

It is suggested not to use hashcode as keys @Cacheable key on multiple method arguments

like image 96
vsingh Avatar answered Oct 03 '22 04:10

vsingh


Yes, you can specify using a Spring-EL expression along these lines:

@Override
@Cacheable(key="#bar.name.concat('-').concat(#bar.id)")
public int foo(Bar bar) {
    ....
}

or define a modified hashCode on bar and call that:

@Override
@Cacheable(key="#bar.hashCodeWithIdName")
public int foo(Bar bar) {
    ....
}
like image 23
Biju Kunjummen Avatar answered Oct 03 '22 03:10

Biju Kunjummen