davioooh davioooh - 1 year ago 130
Java Question

Unable to generate UUID id for my entities

I'm working on a web project using:

  • Spring 4.x (Spring Boot 1.3.3)

  • Hibernate 4.x

  • PostgreSQL 9.x

I'm new to Postgres DB and for my tables I decided to use (for the first time)
identifiers, but I'm having some troubles...

For ID field I used Postgres
type and I set as default value
. All works correctly when I generate a new row directly by a PSQL insert, but I cannot create a new record by my application.

As an example, this is how I declared an entity in my application:

@Table(name = "users")
public class User {

@Type(type = "pg-uuid")
private UUID id;

// other fields and methods...


For this declaration I'm using the
Hibernate annotation.

Find operations work well, but when I try to make an insert I get this exception:

org.springframework.orm.jpa.JpaSystemException: ids for this class must be manually assigned before calling save(): net.myapp.User;

Followiong this tutorial I tried to solve the issue. I changed my entity definition to:

@Table(name = "users")
public class User {

@GeneratedValue(generator = "uuid2")
@GenericGenerator(name = "uuid2", strategy = "uuid2")
@Column(columnDefinition = "BINARY(16)")
private UUID id;

// other fields and methods...

But now I'm getting wrong ID values when I retrieve (existing) data from DB (still haven't tried insert...).

So what is the right way to define ID field in my case?


Using the second definition...

When I try to find by ID, I'm getting:

org.postgresql.util.PSQLException: ERROR: operator does not exist: uuid = bytea
Hint: No operator matches the given name and argument type(s). You might need to add explicit type casts.

When I try to create new record:

org.springframework.dao.InvalidDataAccessResourceUsageException: could not execute statement; SQL [n/a];

Answer Source

I use the following configuration and it works. I am using Glassfish as application server.

@GenericGenerator(name = "uuid", strategy = "uuid2")
@GeneratedValue(generator = "uuid")
@Column(name = "key", unique = true, nullable = false)
private UUID key;

The table key has the Postgres uuid type:

CREATE TABLE billuser.billingresult (key uuid NOT NULL,   .... )...
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download