2

Accessing the DB repeatedly for individual entities is much slower than doing a bulk select. How do I cache a the result of a bulk select into a cache, and later access it individually?

For example, I have a Employee entity:

public class Employee {
  private Integer id;
}

And I have repository that can access it either with bulk select, or individually by id:

public class EmployeeRepository {
  public Map<Integer, Employee> retrieveByEmployeeIds(List<Integer> ids) {
    // impl
  }
  public Employee retrieveByEmployeeId(Integer id) {
    // impl
  }
}

How do I implement it so that when retrieveByEmployeeId(Integer id) is called it will check the same cache as retrieveByEmployeeIds(List<Integer> ids), and if it doesn't exist it'll make a call to the DB, and also storing that cache with the id again?

George
  • 2,820
  • 4
  • 29
  • 56

1 Answers1

1

I have answered similar questions before, for example see (Spring Cache with collection of items/entities).

Essentially, you must implement a custom CacheManager and Cache, the 2 primary interfaces that form the basis of Spring's Cache Abstraction, as described here. It may even extend or delegate to an existing caching provider, but you must "decorate" the existing functionality.

The link I referred to above also contains examples.

Hope this helps give you ideas on how to handle your particular UC.

John Blum
  • 7,381
  • 1
  • 20
  • 30
  • What's your opinion on this design? Is it bad practice to do something like this? – George Feb 26 '19 at 17:04
  • I don't think it is necessarily bad design. I think it depends on the UC. You certainly have to be careful of the queries you run and the results you cache as you could run out of memory pretty quickly, especially in a high volume application. I sort of like the idea of allowing a group of related entities to be loaded at once, especially if it is likely those entities will be operated on next. I used to work on Eligibility Determination Systems for state healthcare (e.g. CHIP, Medicaid, etc) and it was not uncommon to load a "household" of recipients all applying for healthcare. ... – John Blum Feb 26 '19 at 17:48
  • Each member of the household's decision was unique but also dependent on the other members of the household. For example, an adult/parent could be denied while the children might be approved. In this case, the unit was the household of members, for example. – John Blum Feb 26 '19 at 17:50