18

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.

0

4 Answers 4

53

Something like this

unless = "#result==null or #result.size()==0"

More about result and or.

1
  • I just added it. Newbe to SpEL:) Thanks! Commented Sep 22, 2014 at 15:43
18

unless = "#result==null or #result.isEmpty()" works for me.

3
  • This 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.
    – nvoigt
    Commented Feb 15, 2019 at 10:40
  • 3
    probably this was more readable to me instead of #result.size()==0. Also agree with @nvoigt that we should add explanation over any answer.
    – SUMIT
    Commented May 22, 2019 at 18:25
  • adds plenty! a method isEmpty may end up doing something more than a simple check, and is worth it for readability as well
    – Brad Parks
    Commented Oct 23, 2020 at 11:40
0

Just to show an example (Artem Bilan answer is the valid one). My function can return Optional.ofEmpty or Optional of my object

@Cacheable(value = "myCache", unless = "#result == null", key = "@myDao.cacheKey(#id, #languageCode)")
public Optional<MyDTO> getMyStuff(int id, String languageCode) {
... }
0

This worked for me

@Cacheable(cacheNames = "recordCache", key = "#list", unless="#result == null or #result.size() == 0")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.