我有桌子,下面是摘录。

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

如何使availableCount成为非负约束?

最佳答案

如果您需要实际的数据库约束,并且您的架构是由Hibernate生成的,则可以使用@Check批注:

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

07-26 00:54