我有一个想法,使用 Spring Boot 技术实现 UUID 作为 SQL 数据库中的主键。目前,我在如何实现以 UUID 作为主键的自定义固定字符串方面遇到了困境。这是一个例子: 这是一个经典的 UUID:
08d88683-20fc-4884-a523-8f39a06d037f
但我希望我的 UUID 看起来像这样:
USER-08d88683-20fc-4884-a523-8f39a06d037f
如何使用 Spring boot 和 Hibernate 实现这一目标? 这是我的用户模型:
@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;
}
}
在 Hibernate 中实现自定义 id 生成器的最佳方法。 使用以下类,您可以创建自定义生成器:
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();
}
}
然后您可以使用上面创建的类作为 GenricGenerator 实体类中的生成器策略
@Id
@GenericGenerator(name = "string_based_custom_sequence", strategy = "com.package.CustomUserIdGenerator")
@GeneratedValue(generator = "string_based_custom_sequence")
private UUID id;