检查hibernate中允许值的约束注释

Pra*_*kam 1 java sql hibernate jpa

我在数据库中有Consumer表,我在consumer_type列上有检查约束,如下所示:

ALTER TABLE consumer
    ADD CONSTRAINT Check_consumer_consumer_type CHECK (consumer_type IN ('ACCOUNT','ORGANIZATION'))
Run Code Online (Sandbox Code Playgroud)

现在从休眠方面我想添加检查约束注释,它只允许消费者类型表中的"ACCOUNT"和"ORGANIZATION"值.

我应该为此目的使用哪种hibernate/jpa注释?

Boh*_*rdt 5

假设您String在实体中使用了使用的消费者类型,您可以轻松地将其替换为枚举,Java的类型安全性将确保您无法将任何其他内容传递给它.

使用时EnumType.STRING,这些值将作为字符串存储在数据库中(并在加载实体时映射回枚举),因此不需要对数据进行任何更改.


@Entity
public class Consumer {

    public static enum ConsumerType {
        ACCOUNT, ORGANIZATION
    }

    @Enumerated(EnumType.STRING)
    @Column(name="consumer_type", nullable=false)
    private ConsumerType consumerType;

    // Other properties, getters/setters, ...
}
Run Code Online (Sandbox Code Playgroud)