Search code examples
spring-bootehcachespring-cache

Find Object in List Cacheable using Ehcache in spring boot




I want to use cache in my application using ehcache with spring boot.

So i want to cache a list of users and when admin want to find user by email for example not use JpaRepository but i want to find in list of users cachable.

To cache list of users i write below code

    @Override
    @Cacheable(cacheNames = "users")
    public List<User> getList() {
        return userRepository.findAll();
    }

To find a user by email i use for instant code like below :

    List<User> users = getList();
    User userByEmail(String email){
        
        for(User user: users){
            if(user.getEmail().equals(email)){
                return user;
            }
        }
        return null;
    }

I know this is not a good why, but i don't find a good solution.

Anyone help me to use cache correctly and find user using Cacheable list of users.


Solution

  • You should have a method which takes email as an input and returns user with that email from database.

    Add @cacheable on that method so that it will only execute an expensive query to the database first time and add the result to the cache .For any subsequent call to the method it will return the data from cache without actually executing the body of the method.

    @Cacheable("users")
    
    public User getUserByEmail(String email) {
    
       return userRepository.findUserByEmail(email);
    
    }