0

How to achieve the following (if it's possible):

Create table in DB

CREATE TABLE sample (
    id UUID DEFAULT gen_random_uuid(),
    PRIMARY KEY (id)
);

Create Entity

@Entity
public class Sample {

  @Id
  @GeneratedValue(generator = "UUID")
  @GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator")
  @Column(name = "id", columnDefinition = "char(36)")
  @Type(type = "org.hibernate.type.UUIDCharType")
  private String id;

Basically, I want to generate UUID but store it as String in PostgreSQL database and use it as String in Java code too.

Shreyansh Jain
  • 96
  • 1
  • 2
  • 8
  • Relevant: [Persisting UUID in PostgreSQL using JPA](https://stackoverflow.com/questions/11284359/persisting-uuid-in-postgresql-using-jpa) – Tim Biegeleisen May 27 '23 at 10:34
  • You would be far better off generating and storing as UUID, then converting to text (string) on when selected. `select id::text, ... `. – Belayer May 27 '23 at 16:38

1 Answers1

0

Here's how you can adjust your setup to generate a UUID and store it as a string in a PostgreSQL database, while also treating it as a string in your Java code.

First, adjust your PostgreSQL table creation script like so:

CREATE TABLE sample (
    id VARCHAR(36) DEFAULT uuid_generate_v4(),
    PRIMARY KEY (id)
);

Note that the UUID type is set as VARCHAR in this example.

Next, modify your JPA entity class to use a String type for the UUID and set the generation strategy properly:

import java.util.UUID;
import javax.persistence.*;
import org.hibernate.annotations.GenericGenerator;

@Entity
@Table(name = "sample")
public class Sample {
    
    @Id
    @GeneratedValue(generator = "UUID")
    @GenericGenerator(
        name = "UUID",
        strategy = "org.hibernate.id.UUIDGenerator",
        parameters = {
            @org.hibernate.annotations.Parameter(
                name = "uuid_gen_strategy_class",
                value = "org.hibernate.id.uuid.CustomVersionOneStrategy"
            )
        }
    )
    @Column(name = "id", columnDefinition = "VARCHAR(36)")
    private String id;

    // Insert getters and setters here
}

In the PostgreSQL script, the 'uuid_generate_v4()' function is used. If your PostgreSQL database hasn't already activated the 'uuid-ossp' extension, it is required for this functionality. You can activate it with this SQL command:

CREATE EXTENSION IF NOT EXISTS "uuid-ossp";

The 'uuid-ossp' extension provides functions for creating universally unique identifiers (UUIDs) based on several established algorithms.

By using this setup, you are generating UUIDs in the database and storing them as VARCHARs, and you can also use them as Strings in your Java code.

Do keep in mind, however, that storing UUIDs as VARCHARs will consume more storage and might impact performance when compared to storing them as native UUIDs. PostgreSQL's native UUID type takes up only 16 bytes of storage and offers superior indexing and search capabilities.

  • This answer, along with many others you've posted in the last few days, appears likely to have been written (entirely or partially) by AI (e.g., ChatGPT). Please be aware that [posting of AI-generated content is banned here](//meta.stackoverflow.com/q/421831). If you used an AI tool to assist with this answer, I would encourage you to delete it. – NotTheDr01ds Jun 02 '23 at 13:29
  • Since it appears likely to have been written by AI, **readers should review this answer carefully and critically, as it *may* contain fundamental errors and misinformation.** If you observe quality issues and/or have reason to believe that this answer was generated by AI, please leave feedback accordingly. The moderation team can use your help to identify quality issues. – NotTheDr01ds Jun 02 '23 at 13:29