How to use a JVM or database auto-generated UUID identifier with JPA and Hibernate

Introduction In this article, we are going to see how to use a UUID entity identifier that is auto-generated by Hibernate either in the JVM or using database-specific UUID functions. Our Post entity looks as follows: The Post entity has a UUID identifier and a title. Now, let’s see how we can map the Post entity so that the UUID identifier be auto-generated for us.

Hibernate and UUID identifiers

Introduction In my previous post I talked about UUID surrogate keys and the use cases when there are more appropriate than the more common auto-incrementing identifiers. A UUID database type There are several ways to represent a 128-bit UUID, and whenever in doubt I like to resort to Stack Exchange for an expert advice. Because table identifiers are usually indexed, the more compact the database type the less space will the index require. From the most efficient to the least, here are our options: Some databases (PostgreSQL, SQL Server) offer a dedicated… Read More