Search code examples
javahibernatejpaspring-data-jpauuid

Modifying the generated ID, UUID, removing dashes


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;
....

Solution

  • You'll have to 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.IdGenerator")
    @GeneratedValue(generator = "mygen")
    private String id;
    

    Your generator will look like this:

    package com.abc.generator;
    
    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 IdGenerator implements IdentifierGenerator {
    
       @Override
       public Serializable generate(SharedSessionContractImplementor sharedSessionContractImplementor, Object o)
        throws HibernateException {
           return UUID.randomUUID().toString().replace("-", "");
       }
    }