Hibernate non-negative cost constraint

I have a table, below is a snippet.

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 the restriction allowing availableCount to allow only non-negative?

+4
source share
4 answers

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

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

A simple way would be to do it like this:

 public void setAvailableCount(Integer availableCount) { if(availableCount < 0){ throw new IllegalArgumentExcpetion("Must be possive value"); } this.availableCount = availableCount; } 

This will not create a database restriction.

change

If you use JPA annotations, you can create the @ PrePerist-Annotated method:

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

Fix error, loading should work.

0
source

You can use @Min .

 public class Coupon implements Serializable { @Min(0) @Column(name = "available_count") private Integer availableCount = 1; } 

Min : the field or property value must be an integer greater than or equal to the number in the value element

Check out all JPA constants here

They are valid for use in Hibernate.

0
source

Source: https://habr.com/ru/post/1335996/


All Articles