MikaelW
MikaelW

Reputation: 1205

spring-data-redis, empty list attribute value becomes null

I'm in the process of porting some microservices from SpringBoot1.5 to 2.1.

We are using spring-data-redis. it seems the default internal moves from jedis to lettuce.

The thing is we now observe some weird behaviours, when we save an object and then retrieve it, there is a tiny difference:

empty list attributes are replaced with null.

Here is an example:

//repo 
public interface TestRepository extends CrudRepository<Test, String> {}

...

//object
@RedisHash(timeToLive = 60) 
public static class Test{
    @Id private String id;
    int age;
    List<String> friends;
}

...

//saving then retreiving
Test test = new Test("1", 15, Collections.emptyList());
System.out.println(test);
testRepository.save(test);

Test testGet = testRepository.findById("1").get();
System.out.println(testGet);

and here is what happens:

//before
{
  "id": "1",
  "age": 15,
  "friends": []
}

//after 
{
  "id": "1",
  "age": 15
}

the friends empty list has disappeared. This new behaviour affects our code in many places leading to NullPointerExceptions etc.

Apparently, there are multiple serializers available but this doesn't seem to have any effect. Any idea?

https://docs.spring.io/spring-data/data-redis/docs/current/reference/html/#redis:serializer

for reference:

        springBootVersion = '2.1.5.RELEASE'
        springCloudVersion = 'Greenwich.SR1'

Upvotes: 5

Views: 1811

Answers (1)

Zhenyria
Zhenyria

Reputation: 447

I met this problem too. I solved it like this:

@RedisHash(timeToLive = 60) 
public class MyData implements Serializable {

    @Id
    private String id;
    
    
    private List<Object> objects = new ArrayList<>();
}

If i will save MyData with empty list objects, when i pull it from Redis, objects in it will not be null and will be empty list. If i will save 'MyData' with not empty objects, objects not will be lost after deserialization.

Upvotes: 1

Related Questions