When does an autogenerated UUID Id get generated with spring data JPA and hibernate?

Viewed 22

Suppose you have a class with the following UUID primary key:

import javax.persistence.*;
import org.hibernate.annotations.GenericGenerator;

@Entity
public class MyEntity {

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

   // other fields and constructor omitted for brevity
}

When you create a new MyEntity(), the id property is null. That's something I'm used to when the database is responsible for generating the id. In those cases, you must save the entity first before the id is populated. In this case the underlying database is a postgres database with id column type UUID, but the application should be able to generate the Id.

Is there a reason it wouldn't generate automatically and immediately?

Reference: https://thorben-janssen.com/generate-uuids-primary-keys-hibernate/

0 Answers
Related