Fardeen mirza
Fardeen mirza

Reputation: 55

How to get Data from REDIS in Spring Boot based on multiple parameter in where clause like we get in JPA as findByIdAndName

I have a requirement where I need to replace mysql with Redis, so I have method for mysql in JPA as findByIdAndName. And in Redis I am storing key and Object like <Integer,Employee> (Employee is a class and Integer is Id ) so If I want to get employee object from redis based on Integer-Id I can easily get those with findById mentioned below but what if I want to get data based on Employee Name and age so any Idea how to use hashOperation in that way or how to store data in redis in way so that I can get the desired result.

For Example in RedisImplementation:

 public Employee findById(Integer id) {
                    Employee emp = redisTemplate.opsForHash().get("EMPLOYEE_HASH",Id);          
        }

I want to add a method which can get data based on ID and Name like findByIdAndName

Upvotes: 3

Views: 4880

Answers (1)

XII
XII

Reputation: 558

You should use @Cacheable as it enables you to define key with EL expressions.

An example is the following :

@Cacheable(value = "items", key = "#id")
public Item getItem(Integer id) {
    Item item = itemRepository.findById(id).orElseThrow(RuntimeException::new);
    logger.info("Loading data from DB {}", item);
    return item;
}

I am pretty sure @Cacheable supports composite keys like POJOS instead of primitives as keys. Also if you do not specify key explicitly it will take the arguments of the method that has the annotation as a key.

A really good documentation / tutorial is the following one https://springhow.com/spring-boot-redis-cache/

Hope I helped :)

Upvotes: 1

Related Questions