Home > database >  Modifying the generated ID, UUID, removing dashes
Modifying the generated ID, UUID, removing dashes

Time:06-01

Due to compatibility reasons with existing systems, I have to store the UUID type as varchar without dashes. What would be the simplest solution to do this?

I have created a sample class below to demonstrate the question. When the instance of the class is persisted, the UUID is in the DB fine, just with the dashes in the tab1_id column e.g. 583cfe1a-d671-47f9-9cd5-3f1e8f717856. What I would need is: 583cfe1ad67147f99cd53f1e8f717856. So the question is how I could change the generated id after its generation.

I am using spring-boot and hibernate as JPA implementation. Any constructive response is appreciated. Thanks in advance.

@Entity
@Table(name = "tab1")
@XmlRootElement
public class Tab1 implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(generator = "UUID")
@GenericGenerator(
    name = "UUID",
    strategy = "org.hibernate.id.UUIDGenerator"
)
@Column(name = "tab1_id", updatable = false, nullable = false, columnDefinition = "uuid")
@Type(type = "org.hibernate.type.UUIDCharType")
private UUID tab1Id;
@Column(name = "name")
private String name;
....

CodePudding user response:

You'll have implement a custom ID generator and your entity will have an ID of String as it's no longer going to be a valid UUID.

Something like this will work

@Id
@GenericGenerator(name = "mygen", strategy = "com.abc.generator.IDGen")
@GeneratedValue(generator = "mygen")
private String id;

Your generator will look like this:

package com.abc.generator.model;

import java.io.Serializable;
import java.util.UUID;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.IdentifierGenerator;

public class IDGen implements IdentifierGenerator {

   @Override
   public Serializable generate(SharedSessionContractImplementor sharedSessionContractImplementor, Object o)
    throws HibernateException {
       return UUID.randomUUID().toString().replace("-", "");
   }
}

CodePudding user response:

Do you need it persisted on database? If that is the case I guess it wouldn't be possible. But if you want to retrieve it without the dashes just do the getUUID method of your entity class return a string without the dashes.

  • Related