Hibernate primary key: Integer vs UUID

Опубликовано: 11 Май 2025
на канале: TramoTech
704
17

For those who need to decide which primary key type to choose, I conducted a test myself, initially on PostgreSQL, and I believe the results would be similar for Oracle.
The test involved creating and saving 1 million records using Java (with Hibernate) as the client:

strategy Field Type entities creation elapsed time (ms) saving entities
elapsed Time (ms) Table Size
(mb) Index Size
(mb)
UUID String 7768 181184 80 73
UUID UUID 7763 172367 57 37
Sequence Long 10036 163351 49 21

UUIDs consist of two Longs, which means they require double the space compared to a single Long. However, despite this overhead, we observed that the creation of entities using UUIDs at the client-side is faster compared to using sequences. This is due to the fact that UUIDs allow for client-side ID generation, reducing the need for round trips to the database during entity creation (Despite efforts to minimize its impact for sequences, we still observe its effect).
On the other hand, saving entities with Long IDs takes less time than UUIDs. This is because Longs require less storage space and hence result in quicker database operations.

In my case, working with microservices and distributed systems, the preferred primary key type turned out to be UUID

https://tramotech.de