hibernatejpaspring-bootuuid

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.


Solution

  • 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() ?