2016-06-13 127 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>