spring-data-jpa 在主键Sping Boot 中使用附加字符串作为前缀的UUID

kr98yfug  于 2022-11-10  发布在  Spring
关注(0)|答案(1)|浏览(188)

我有一个想法,在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;
    }
}
bprjcwpo

bprjcwpo1#

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

相关问题