Files
spring-boot-demo/redis/docs/05-redis-hash.md
T

2.3 KiB

Home | Prev: JSON serializers | Next: Hash TTL and keyspace events

5. @RedisHash: what a repository actually writes

@RedisHash turns a class into a Redis hash and lets you use a CrudRepository. It does not use RedisTemplate's value serializer at all: it converts the entity to a map of field names and text values, so there is no JDK-serialization problem here. What surprises people is the number of keys.

Person has @Id, one @Indexed field (lastName) and two plain fields. Saving two people (08-redis-hash.txt) creates six keys:

$ redis-cli -p 6390 KEYS '*' | sort
person
person:1
person:1:idx
person:2
person:2:idx
person:lastName:Mhatre
Key Type Purpose
person:1 hash The entity: _class, age, firstName, id, lastName
person set Every id in the keyspace. count() reads this set (see chapter 6)
person:lastName:Mhatre set The secondary index for the @Indexed field: ids with that value
person:1:idx set For each entity, the index sets it is in, so a delete or update can clean them

findByLastName works because of the index: it reads person:lastName:Mhatre and loads each hash.

The _class field in the hash records the Java type (com.ankurm.redis.hash.Person), so this is a type-name dependency like the ones in chapter 4.

Deleting and updating

deleteById("1") removes person:1, person:1:idx, the id from person and the id from person:lastName:Mhatre. The transcript's final section shows the survivors. The bookkeeping is done by Spring Data Redis in the application, not by Redis, which is why chapter 6 matters: when Redis removes the hash on its own, nothing does that bookkeeping.

Going deeper

Home | Prev: JSON serializers | Next: Hash TTL and keyspace events