sergtk
sergtk

Reputation: 10974

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?

Upvotes: 4

Views: 6772

Answers (4)

Sebastian D'Agostino
Sebastian D'Agostino

Reputation: 1675

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

Upvotes: 2

axtavt
axtavt

Reputation: 242766

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 { ... }

Upvotes: 5

Christian Kuetbach
Christian Kuetbach

Reputation: 16060

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.

Upvotes: 1

lweller
lweller

Reputation: 11327

make use of Hibernate Validator project

Upvotes: 3

Related Questions