15

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
  • 352
  • 2
  • 6
  • 17

4 Answers4

49

Something like this

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

More about result and or.

jumping_monkey
  • 5,941
  • 2
  • 43
  • 58
Artem Bilan
  • 113,505
  • 11
  • 91
  • 118
18

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

NanoNova
  • 829
  • 10
  • 19
  • 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 Feb 15 '19 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 May 22 '19 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 Oct 23 '20 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) {
... }
Mircea Stanciu
  • 3,675
  • 3
  • 34
  • 37
0

This worked for me

@Cacheable(cacheNames = "recordCache", key = "#list", unless="#result == null or #result.size() == 0")
David AJ
  • 29
  • 1
  • 4