Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Generate an auto UUID using Hibernate on spring boot

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.

like image 873
mattts Avatar asked Jul 13 '17 17:07

mattts


People also ask

How does Hibernate generate UUID?

Hibernate supports 2 of them: The default strategy generates the UUID based on random numbers (IETF RFC 4122 Version 4). You can also configure a generator that uses the IP address of the machine and a timestamp (IETF RFC 4122 Version 1).

How a UUID is generated?

Version-1 UUIDs are generated from a time and a node ID (usually the MAC address); version-2 UUIDs are generated from an identifier (usually a group or user ID), time, and a node ID; versions 3 and 5 produce deterministic UUIDs generated by hashing a namespace identifier and name; and version-4 UUIDs are generated ...


1 Answers

Can you try?

    @Id
    @GeneratedValue(generator = "uuid2")
    @GenericGenerator(name = "uuid2", strategy = "org.hibernate.id.UUIDGenerator")
    @Column(name = "id", columnDefinition = "VARCHAR(255)")
    private UUID id;
like image 106
fg78nc Avatar answered Sep 18 '22 19:09

fg78nc