skip to Main Content

First of all, I create a parent class implements Serializable, then create a child class to extends it. And I use RedisTemplate with GenericFastJsonRedisSerializer config to put data into redis, but when I get it back from Reids, the data is changed.Please tell me why and how to fix it?

@Data
public class People implements Serializable {
    public Long id;
    public String name;
}

@EqualsAndHashCode(callSuper = true)
@Data
public class Student extends People{
    private String sName;
}

    @Bean(name = "redisTemplate")
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(factory);

        RedisSerializer keySerializer = new StringRedisSerializer();
        RedisSerializer valueSerializer = new GenericFastJsonRedisSerializer();

        redisTemplate.setDefaultSerializer(valueSerializer);
        redisTemplate.setKeySerializer(keySerializer);
        redisTemplate.setValueSerializer(valueSerializer);
        redisTemplate.setHashKeySerializer(keySerializer);
        redisTemplate.setHashValueSerializer(valueSerializer);

        RedisUtil.init(redisTemplate);
        return redisTemplate;
    }
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Test
    public void cacheDeserialize(){
        Student student = new Student();
        student.setId(11111111111111111L);
        student.setName("parent name");
        student.setSName("child name");
        redisTemplate.opsForValue().set("parent-child-test", student);
        Object value = redisTemplate.opsForValue().get("parent-child-test");
        System.out.println(value); // print:Student(sName=child name), but I wish it print Student(id=111111111,name=parent name,sName=child name)
    }

But:
Test result image

2

Answers


  1. Chosen as BEST ANSWER

    Solution one: use Lombok.annotation @ToString(callSuper = true) in chile class;

    Solution two: take parent class attrs to child class;


  2. You need to implement both classes with Serializable and define serialVersionUID like this

    public class People implements Serializable {
    
    private static final long serialVersionUID = 7156526077883281623L;
    
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search