Implementing Postgres UUID primary keys with Spring Boot and Hibernate
An alternative to auto-increment sequential primary keys, is using a Universally Unique Identifier
. Spring Boot and Hibernate support them and you can use them using Spring Data’s autogenerated SQL, JPQL and native queries.
As a demonstration project, you can clone spring-boot-hibernate-postgres-uuids.
To run the examples, you’ll need docker
and docker-compose
installed. You can setup the project by running docker-compose up
in the docker
directory. Doing this will create a new database, and automatically install the uuid-ossp
extension.
Creating the Entity model
The project uses a User
model as an example. You can setup Hibernate to use a UUID
for its entity ID by using the annotations below.
Creating the Spring Data Repository
You can create a CrudRepository
using a UUID
as the identifier.
Now you can use the CrudRepository
autogenerated retrieve functions.
If you create a projection, it will work with that too.
You can use the projection in combination with a JPQL query,
and a native query:
You’ll notice that the native query requires that the UUID
be cast to a VARCHAR
datatype. This is because currently Hibernate does not correctly recognise the raw UUID
type.