javapostgresqlspring-data-r2dbc

Spring Data R2DBC PostgreSQL not saving new record with UUID @Id


I have a simple entity, consisting of two UUIDs:

@Table("library")
public class LibraryDao {
    @Id
    private UUID id;
    @NonNull
    private UUID ownerId;
}

I have a corresponding table in PostgreSQL:

CREATE TABLE IF NOT EXISTS library (id UUID PRIMARY KEY, owner_id UUID NOT NULL);

I am using the correct R2DBC drivers (io.r2dbc:r2dbc-postgresql and org.postgresql:postgresql).

To this point, everything works. My applpication runs. But…

Because PostgreSQL does not – at least according to the documentation – have an auto-generating function for UUIDs, I set the id when creating a new LibraryDao instance.

However, when I call the save method in my Repository, I get an exception: Failed to update table [library]. Row with Id [0ed4d7c0-871a-4473-8997-4c9c1ec67a00] does not exist.

It appears that save is being interpretted as update, without a fallback to insert if it doesn't exist.

How am I supposed to insert a new record into my database?


Solution

  • Despite the PostgreSQL documentation, there is a way to auto-generate UUIDs using the pgcrypto extension (for v4 UUIDs). (Process based on using pgAdmin GUI.)

    In the Query Tool:

    Then, change the column definition with to ... id UUID PRIMARY KEY DEFAULT gen_random_uuid(), ...

    And it works.