简体   繁体   English

Hibernate非负值约束

[英]Hibernate non-negative value constraint

I have the table, the snippet below. 我有桌子,下面的片段。

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

How to make constraint to allow for availableCount be only non-negative? 如何使约束允许availableCount只是非负的?

If you need an actual database constraint, and your schema is generated by Hibernate, you can use @Check annotation: 如果您需要实际的数据库约束,并且您的架构是由Hibernate生成的,则可以使用@Check注释:

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

You can use @Min . 你可以使用@Min

public class Coupon implements Serializable {

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

}

Min documentation: The value of the field or property must be an integer value greater than or equal to the number in the value element 最小文档:字段或属性的值必须是大于或等于value元素中的数字的整数值

Check all JPA constaints here 在这里检查所有JPA constaints

They are valid to be used in Hibernate 它们在Hibernate中有效

The easy way would be to make it like this: 简单的方法就是这样:

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

This won't create a databse constraint. 这不会创建数据库约束。

edit: 编辑:

If you take use of JPA-Annotations, you can create an @PrePerist-Annotated method: 如果您使用JPA-Annotations,则可以创建@ PrePerist-Annotated方法:

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

The commit should fail, loading should work. 提交应该失败,加载应该工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM