Spring cacheable - filter out empty collections using SpEL
11,515
Solution 1
Something like this
unless = "#result==null or #result.size()==0"
Solution 2
unless = "#result==null or #result.isEmpty()"
works for me.
Author by
user2512231
Updated on June 18, 2022Comments
-
user2512231 almost 2 years
I wanted to know is there a way to use SpEL in order to filter out values like empty collections.
My cache currently filters out null values:
@Cacheable(value = "groupIdToGroupNames",unless = "#result == null") public Map<Long, Collection<String>> findAllBySearchCustomerKey(final long groupId) { return idToNameClient.findAllGroupMembersById(groupId); }
I'm trying to find a way to filter out the groups that are of size 0 but not null. Is there a way of doing that by using params for @Cacheable?
Any help would be much appreciated.
-
user2512231 over 9 yearsI just added it. Newbe to SpEL:) Thanks!
-
nvoigt about 5 yearsThis does not seem to add anything new over the accepted 5 year old answer. It will probably be deleted by reviewers. If you think your answer makes a significant difference, you may want to add an explanation on how this is better than the existing answers.
-
SUMIT almost 5 yearsprobably this was more readable to me instead of #result.size()==0. Also agree with @nvoigt that we should add explanation over any answer.
-
Brad Parks over 3 yearsadds plenty! a method
isEmpty
may end up doing something more than a simple check, and is worth it for readability as well