Zeta
Zeta

Reputation: 534

Using annotations to control the Redis object serialization?

When you have an object to persist to Redis using Spring Redis Framework, the object is saved to Redis with the key name as given in the object property.

Given:

Class Person {

    String name;
    String age;

    //getter and setter.

}

Now when this object is serialized and persisted to Redis using

redisTemplate.opsForHash().put("PERSON", device.hashCode(), person);

the result within Redis looks like

PERSON SOMEHASH {name:abc,age:30}

It is very convenient to persist the data but would it be more flexible to have annotations to save according to a some naming format the developer want?

Say

class Person {

        @(Name = Person_NAME)
        String name;
        @(Name = Person_AGE)
        String age;

        //getter and setter.

    }

Upvotes: 1

Views: 1088

Answers (1)

mp911de
mp911de

Reputation: 18119

Spring Data Redis uses serializers to control how data is represented. Spring Data Redis brings various serializer implementations.

It looks like you're using the JSON serializer that is built with Jackson2. This means you can control the output by applying Jackson2 annotations to your classes.

class Person {

    @JsonProperty(Person_NAME)
    String name;

    @JsonProperty(Person_AGE)
    String age;

    //getter and setter.

}

Upvotes: 2

Related Questions