Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 605
sergtk Avatar asked Dec 21 '22 19:12

sergtk


1 Answers

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 { ... }
like image 84
axtavt Avatar answered Dec 29 '22 00:12

axtavt