Hibernate非负值约束

时间:2011-01-18 14:25:31

标签: java database hibernate check-constraints

我有桌子,下面的片段。

    package test;

    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id;
    import javax.persistence.Table;
    import javax.persistence.UniqueConstraint;

    @Entity
    @Table(uniqueConstraints = { @UniqueConstraint(columnNames = "code")},
           name = "coupons")
    public class Coupon implements  Serializable {

        private static final long serialVersionUID = 5534534530153298987L;

        @Id
        @GeneratedValue
        @Column(name = "id")
        private long id;

        @Column(name = "available_count")
        private Integer availableCount = 1;

        public Integer getAvailableCount() {
            return availableCount;
        }

        public void setAvailableCount(Integer availableCount) {
            this.availableCount = availableCount;
        }
    }

如何制定约束以允许availableCount只是非负面的?

4 个答案:

答案 0 :(得分:5)

如果您需要实际的数据库约束,并且您的架构是由Hibernate生成的,则可以使用@Check注释:

@Entity
@Table(uniqueConstraints = { @UniqueConstraint(columnNames = "code")},
        name = "coupons")
@Check(constraints = "available_count >= 0")
public class Coupon implements  Serializable { ... }

答案 1 :(得分:3)

答案 2 :(得分:1)

您可以使用 @Min

public class Coupon implements Serializable {

    @Min(0)
    @Column(name = "available_count")
    private Integer availableCount = 1;

}

Min 文档:字段或属性的值必须是大于或等于value元素中的数字的整数值

检查所有JPA constaints here

它们在Hibernate

中有效

答案 3 :(得分:0)

简单的方法就是这样:

public void setAvailableCount(Integer availableCount) {
    if(availableCount < 0){
        throw new IllegalArgumentExcpetion("Must be possive value");
    }
    this.availableCount = availableCount;
}

这不会创建数据库约束。

修改

如果您使用JPA-Annotations,您可以创建@ PrePerist-Annotated方法:

@PrePersist
public void something(){
    if(availableCount < 0){
        throw new IllegalArgumentExcpetion("Must be possive value");
    }
}

提交失败,加载应该有效。