I would like to add some caching in place but so fare all the examples I saw only show examples of caching simple entities (like the Spring book example) which works perfectly when using @Cacheable, @CachePut etc..
However, given this simple User - Roles examples:
public class User {
private String username
private List<Role> roles
}
Database side, 3 tables
user
id | username
1 | bob
user_role
user_id | role_id
1 | 1
1 | 2
1 | 3
role
id | name
1 | role1
2 | role2
3 | role3
a simple service that returns a user (with its roles), and this is what I would like to cache
@Cacheable(....)
public User getUserByUsername(username) {
// SQL that joins the 3 tables and return a user with its roles
User user = dao.getUserByusername(username)
}
An other service that will add a new role to a user (so it indirectly modifies the user object), hence the cache needs to be updated
//@CachePut(Yep.. this isn't going to work is it)
public void addRoleToUser(username, role_id) {
// SQL to insert a row into the user_role table
dao.addRoleToUser(username, role)
}
My question is: Is there a pattern / solution to have the cache directly updated after a role is added (like when using the @CachePut on simple entities) ?
Or is the only solution to have the @CacheEvict on addRoleToUser forcing the next call to getUserByUsername retrieve the data from the database ?
I'm asking this because, performance wise, I would much prefer to have the cache updated directly when a role is added instead of clearing the cache and forcing a new database hit.