我有一个想法,在SQL数据库中用spring Boot 技术实现UUID作为主键。目前,我在如何实现一个用UUID作为主键的自定义固定字符串上遇到了一个难题。下面是一个示例:这是一个典型的UUID:
08d88683-20fc-4884-a523-8f39a06d037f
但我想我的UUID看起来像这样:
USER-08d88683-20fc-4884-a523-8f39a06d037f
我如何使用Sping 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;
}
}
1条答案
按热度按时间bprjcwpo1#
在Hibernate中实现自定义ID生成器的最佳方法。使用以下类可以创建自定义生成器:
然后,您可以使用上面创建的类作为GenricGenerator实体类中的生成器策略