Search code examples
javaredisspring-dataspring-data-redis

How can I search a redis hash table for entities that have a particular values using spring data?


I have a RedisHash table that I've model in spring data like this:

@RedisHash("Entity")
@Data
@AllArgsConstructor
public class Entity implements Serializable {
  private String id;
  private String status;
  private String name;
}

I have an EntityRepository like this:

@Repository
public interface EntityRepository extends CrudRepository<Entity, String> {}

I then have an EntityService like this:

@Service 
public class EntityService {
  @Autowired
  private EntityRepository entityRepository;

  public List<Entity> getAllByName(String name) {
    // Code that gets all Entities stored in my redis table that have a certain name
  }

  public List<Entity> getAllByStatus(String status) {
    // Code that gets all Entities stored in my redis table that have a certain status
  }

How can I search redis for all Entities that have a certain name / have a certain status?


Solution

  • I followed the documentation here and was able to solve my problem. I added the QueryByExampleExecutor interface to my repository like this:

    @Repository
    public interface EntityRepository extends CrudRepository<Entity, String>, QueryByExampleExecutor<Entity> {}
    

    Using the Example class I implemented getAllByName like this:

    public List<Entity> getAllByName(String name) {
        Entity entity = new Entity();
        entity.setName(name);
    
        Example<Entity> example = Example.of(entity);
        entityRepository.findAll(example);
        //...
    }