简体   繁体   中英

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

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:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM