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