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?
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 { ... }
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With