【问题标题】:check constraint annotation for allowed values in hibernate检查约束注释以获取休眠中的允许值
【发布时间】:2015-10-27 11:54:00
【问题描述】:

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

ALTER TABLE consumer
    ADD CONSTRAINT Check_consumer_consumer_type CHECK (consumer_type IN ('ACCOUNT','ORGANIZATION'))

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

为此我应该使用哪个 hibernate / jpa 注释?

【问题讨论】:

    标签: java sql hibernate jpa


    【解决方案1】:

    假设您的实体中有使用 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, ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-17
      • 1970-01-01
      • 2018-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-28
      相关资源
      最近更新 更多