21

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.

Neil Stockton
  • 11,383
  • 3
  • 34
  • 29
mattts
  • 313
  • 2
  • 7
  • 20

5 Answers5

27

Can you try?

    @Id
    @GeneratedValue(generator = "uuid2")
    @GenericGenerator(name = "uuid2", strategy = "org.hibernate.id.UUIDGenerator")
    @Column(name = "id", columnDefinition = "VARCHAR(255)")
    private UUID id;
fg78nc
  • 4,774
  • 3
  • 19
  • 32
16

u could use some events like @PrePersist to populate UUID field https://docs.jboss.org/hibernate/orm/4.0/hem/en-US/html/listeners.html

but why just not assign uuid when object is created uuid = UUID.randomUUID() ?

Bartun
  • 549
  • 2
  • 12
  • 3
    > but why just not assign uuid when object is created uuid = UUID.randomUUID() ? because sometimes you need to support other tools which doesn't use hibernate and do inserts directly – long Nov 01 '18 at 12:00
14

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.

Shadman R
  • 171
  • 1
  • 7
7

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;
Turdaliev Nursultan
  • 2,538
  • 1
  • 22
  • 28
0
    @Id
    @GeneratedValue
    private UUID productUUID;

This will generate a random uuid when Entity record is saved

slinger
  • 140
  • 1
  • 2
  • 7