Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

uuid

default

h2

In the H2 database, on a table with a column of UUID data type, how do we specify that we want H2 to generate a UUID value by default when an INSERT omits that field?

I know how to generate a UUID. I have read the Question, How to insert a specific UUID in h2 database?.

My question is about how to ask H2 to generate the UUID value on my behalf.

like image 880
Basil Bourque Avatar asked Dec 13 '16 01:12

Basil Bourque


People also ask

How to generate UUID in JPA?

Generating UUIDs using JPA 3.1 Since JPA 3.1, you can annotate a primary key attribute with @GeneratedValue and set the strategy to GenerationType. UUID. Based on the specification, your persistence provider shall generate a UUID value based on IETF RFC 4122. Let's try this mapping and persist a new Book entity object.

How do I add a UUID to a table?

Use ALTER TABLE to add a UUID column to an existing table. Create a table test_alter without a UUID column. Use ALTER TABLE to add a UUID column to test_alter . You can specify the default clause, GENERATED BY DEFAULT.

What is the data type for UUID?

The UUID data type is considered a subtype of the STRING data type, because UUID values are displayed in their canonical textual format and, in general, behave the same as string values in the various SQL operators and expressions.

What is UUID in Hibernate?

This annotation defines the Hibernate type mapping. Using “uuid-char” instructs Hibernate to store the UUID as a String, instead of the binary value. This way, it can be written to and read from a VARCHAR(36) column without the need for any pre-processing on our side.


2 Answers

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).

like image 157
Thomas Mueller Avatar answered Sep 17 '22 14:09

Thomas Mueller


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

like image 36
JeSa Avatar answered Sep 16 '22 14:09

JeSa