How to Generate an auto UUID using Hibernate on spring boot

Viewed 50699

What I am trying to achieve is generate a UUID which is automatically assigned during a DB Insert. Similar to the primary key column named "id" generating an id value.

The model values looks something like this:

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(nullable = false)
private Long id;


@GeneratedValue(generator = "uuid2")
@GenericGenerator(name = "uuid2", strategy = "uuid2")
@Column(name = "uuid", columnDefinition = "BINARY(16)")
private UUID uuid;

But when the DB insert is done. the "uuid" is empty.

Help is greatly appreciated. And if I am asking an obvious stupid question I am sorry.

4 Answers

There has been lot of changes in the framework and as tested in Spring Boot 2.2.5 with MySQL v5.7 (Should work with all 2.0 versions but need to check) UUID can be auto generated like below

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="id", insertable = false, updatable = false, nullable = false)
private UUID id;

This will store it in binary format in compact manner (good for storage). If for some reason one needs to store UUID in Varchar field as human readable (dash separated values) it can be done as below

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Type(type="uuid-char")
@Column(name="id", columnDefinition = "VARCHAR(255)", insertable = false, updatable = false, nullable = false)
private String id;

By default Hibernate maps UUID with binary format, hence to change the format we need to provide hint using the Type annotation.

Following worked for me:

@Id
    @GeneratedValue(generator = "UUID")
    @GenericGenerator(
            name = "UUID",
            strategy = "org.hibernate.id.UUIDGenerator"
    )
    @Column(name = "id", updatable = false, nullable = false)
    private UUID id;
Related