How to Auto generate UUID value for non-primary key using JPA

Viewed 3764

I have Spring boot application where I am using JPA layer to talk to PostgreSQL. I have a non-primary key of type UUID which I want to auto generate on call of save method. I annotated the attribute with @GeneratedValue but the column value is null on insert.

@Column(name = "USER_UUID")
@GeneratedValue(strategy = GenerationType.AUTO)
private UUID userUuid;

Also I have created the column as:

ADD COLUMN IF NOT EXISTS user_uuid uuid UNIQUE DEFAULT uuid_generate_v4();

How to auto generate the non-primary UUID value in this case?

1 Answers

You can use JPA callbacks.

 @PrePersist
    protected void onCreate() {
        setUserUuid(java.util.UUID.randomUUID());
    }
Related