2016-06-13 112 views
0

我需要實現實體數據字段範圍約束:Bean驗證範圍制約

@Entity 
@Table(name = "T_PAYMENT") 
public class Payment extends AbstractEntity { 

    //.... 

    //Something like that 
    @Range(minValue = 80, maxValue = 85) 
    private Long paymentType; 

} 

我已經創建的驗證服務,但要實現許多這些情況。

如果插入的數字超出範圍,我需要應用程序拋出異常。

+1

您可以通過以下標註定義範圍。 '@Max(85)\t @Min(5)'並且如果您想爲此驗證定義自定義消息,那麼您需要創建自定義約束。請參閱此鏈接(http://www.thejavageek.com/2014/05/24/jpa-constraints/) – ypp

+0

http://stackoverflow.com/questions/5129825/difference-between-max-and-decimalmax-和分鐘和 - decimalmin –

回答

2

你需要hibernate-validator

Please refer to this official documentation.

註釋

@Range(min=, max=) 

支持的數據類型

BigDecimal, BigInteger, CharSequence, byte, short, int, long and the respective wrappers of the primitive types 

使用

Checks whether the annotated value lies between (inclusive) the specified minimum and maximum 
1

隨着hibernate-validator依賴可以定義範圍檢查

@Min(value = 80) 
@Max(value = 85) 
private Long paymentType; 

pom.xml添加下面的依賴

<dependency> 
     <groupId>org.hibernate</groupId> 
     <artifactId>hibernate-validator</artifactId> 
     <version>{hibernate.version}</version> 
    </dependency>