1

I had an idea to implement UUID as my primary key in the SQL database with spring boot technology. Currently, I have a dilemma on how to implement a custom fixed string with UUID as my primary key. Here is an example: This is a classic UUID:

08d88683-20fc-4884-a523-8f39a06d037f

But I wanted to my UUID looks something like this:

USER-08d88683-20fc-4884-a523-8f39a06d037f

How could I achieve that with Spring boot and Hibernate? Here is my user model:

@Data
@Entity
@Table( name = "users",
        uniqueConstraints = {
                @UniqueConstraint(columnNames = "username"),
                @UniqueConstraint(columnNames = "email")
        })
@NoArgsConstructor
public class User {
    @Id
    @GeneratedValue(generator = "uuid2")
    @GenericGenerator(name = "uuid2", strategy = "uuid2")
    @Column(name = "id", updatable = false, nullable = false, columnDefinition = "VARCHAR(36)")
    @Type(type = "uuid-char")
    private UUID id;

    @NotBlank
    @Size(max = 20)
    private String username;

    @NotBlank
    @Size(max = 50)
    @Email
    private String email;

    @NotBlank
    @Size(max = 120)
    private String password;

    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable( name = "user_roles",
            joinColumns = @JoinColumn(name = "user_id"),
            inverseJoinColumns = @JoinColumn(name = "role_id"))
    private Set<Role> roles = new HashSet<>();

    public User(String username, String email, String password) {
        this.username = username;
        this.email = email;
        this.password = password;
    }
}
Sanady_
  • 68
  • 10

1 Answers1

0

The best way to implement custom id generator in Hibernate. Using the following class you can create Custom Generator:

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

public class CustomUserIdGenerator implements IdentifierGenerator {
    @Override
    public Serializable generate(SharedSessionContractImplementor sharedSessionContractImplementor, Object o) throws HibernateException {
        return "USER-"+ UUID.randomUUID();
    }
}

And then you can use the above created class as the generator strategy in entity class for the GenricGenerator

@Id
@GenericGenerator(name = "string_based_custom_sequence", strategy = "com.package.CustomUserIdGenerator")
@GeneratedValue(generator = "string_based_custom_sequence")
private UUID id;