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?
CodePudding user response:
The UUID can be auto-generated, if you generate it by yourself Hibernate sees the entity with an id and try to update it.
To auto-generate the uuid just use the following annotations on your fields:
@GeneratedValue(generator = "UUID")
@GenericGenerator(
name = "UUID",
strategy = "org.hibernate.id.UUIDGenerator",
)
source: https://thorben-janssen.com/generate-uuids-primary-keys-hibernate/
CodePudding user response:
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:
select * from pg_extensionand check that pgcrypto is not listed.create extension pgcryptoto install it; it comes with the default installation.
Then, change the column definition with to ... id UUID PRIMARY KEY DEFAULT gen_random_uuid(), ...
And it works.
