Generate UUID values by default for each row on column of UUID type in H2 Database Engine

In SQL

You can use built-in function RANDOM_UUID():

create table test(id int primary key, data uuid default random_uuid());
insert into test(id) values(1);
select * from test;

Note that using the UUID type (or any other randomly generated data that doesn't have any natural ordering) as the primary key will result in performance problems if there are more than a few million rows (with relational databases in general, not just with H2).


In JPA/Hibernate

After googling for hours I've created a simple solution for JPA or Hibernate, according to @Thomas Mueller.

@Id
@GeneratedValue(generator = "UUID")
@GenericGenerator(
        name = "UUID",
        strategy = "org.hibernate.id.UUIDGenerator"
)
@Column(name = "ID", updatable = false, nullable = false)
@ColumnDefault("random_uuid()")
@Type(type = "uuid-char")
@Getter
@Setter
private UUID id;

So @Type(type = "uuid-char") makes your field a VARCHAR(255) if you need it (it's binary by default)

And @ColumnDefault("random_uuid()") puts the default value for generated table DDL

Tags:

Uuid

Default

H2