开发者

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-negati开发者_C百科ve?


If you need an actual database constraint, and your schema is generated by Hibernate, you can use @Check annotation:

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


make use of Hibernate Validator project


You can use @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

Check all JPA constaints here

They are valid to be used in 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:

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

The commit should fail, loading should work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜