I've read that caching a findAll method using Ehcache 3 is considered an anti-pattern. Why is that exactly?
For demo purposes, I've created a simple Java application that implements caching using Ehcache 3.
So, here's a findById method that exploits caching.
public Person findById(Long id) {
Optional<Person> optPerson = personCache.get(id);
if (optPerson.isPresent()) {
return optPerson.get();
}
try (PreparedStatement statement = connection.prepareStatement("SELECT * FROM person WHERE id = ?")) {
statement.setLong(1, id);
ResultSet rs = statement.executeQuery();
if (rs.next()) {
Long actualId = rs.getLong("id");
String firstName = rs.getString("first_name");
String lastName = rs.getString("last_name");
Integer age = rs.getInt("age");
Person person = new Person(actualId, firstName, lastName, age);
personCache.put(person);
return person;
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
return null;
}
It works as expected.
However, I also would like to store the findAll (SELECT * FROM person) query. I'm not sure how to do that, and why is it an anti-pattern.
Is it because the number of tuples in the database is unknown? Caching too much can be rather counter-productive, but there's still a solution to cache only when findAll would return less than X values.
How do I go about storing findAll with Ehcache in pure Java?