Search code examples
javaspringredisspring-data-redis

Update Single Field of Hash in Redis


Is it possible to update single field of Student object without needing other ones? Lets say I want to update grade field.

import com.ahmetk.redis.redishll.model.Student;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;


@Repository
public interface StudentRepository extends CrudRepository<Student, String> {}


@RedisHash("Student")
@Data
@Getter
@Setter
@AllArgsConstructor
public class Student implements Serializable {

   public enum Gender {
      MALE, FEMALE
   }

   private String id;
   private String name;
   private Gender gender;
   private int grade;

   @Override
   public String toString() {
      return "Student{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", gender=" + gender + ", grade=" + grade + '}';
   }
}



    @Test
    public void whenDeletingStudent_thenNotAvailableOnRetrieval() throws Exception {
        final Student student = new Student("Eng2015001", "John Doe", Student.Gender.MALE, 1);
        studentRepository.save(student);
        studentRepository.delete(student.getId());
        final Student retrievedStudent = studentRepository.findOne(student.getId());
        assertNull(retrievedStudent);
    }

Solution

  • you can look at this - https://docs.spring.io/spring-data/data-redis/docs/current/reference/html/#redis.repositories.partial-updates

    the template in the example in the docs is an instance of RedisKeyValueTemplate

    @Autowired
    private RedisKeyValueTemplate redisKVTemplate;
    redisKVTemplate.update(entity)