Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01B38FGKKam5SCGgwgduVAh3
49 lines
2.3 KiB
Markdown
49 lines
2.3 KiB
Markdown
[Home](../README.md) | Prev: [JSON serializers](04-json-serializers.md) | Next: [Hash TTL and keyspace events](06-hash-ttl-and-keyspace-events.md)
|
|
|
|
# 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](../src/main/java/com/ankurm/redis/hash/Person.java) has `@Id`, one `@Indexed` field
|
|
(`lastName`) and two plain fields. Saving two people
|
|
([08-redis-hash.txt](output/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](06-hash-ttl-and-keyspace-events.md)) |
|
|
| `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](04-json-serializers.md).
|
|
|
|
## 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](06-hash-ttl-and-keyspace-events.md)
|
|
matters: when Redis removes the hash on its own, nothing does that bookkeeping.
|
|
|
|
## Going deeper
|
|
|
|
- [RedisHashTest](../src/test/java/com/ankurm/redis/RedisHashTest.java)
|
|
- [Spring Data Redis: Redis Repositories](https://docs.spring.io/spring-data/redis/reference/redis/redis-repositories/usage.html)
|
|
|
|
[Home](../README.md) | Prev: [JSON serializers](04-json-serializers.md) | Next: [Hash TTL and keyspace events](06-hash-ttl-and-keyspace-events.md)
|