Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between @size(max = value ) and @min(value) and @max(value)

I want to do some domain validation. In my object I have one integer.

Now my question is: if I write

@Min(SEQ_MIN_VALUE) @Max(SEQ_MAX_VALUE) private Integer sequence; 

and

 @Size(min = 1, max = NAME_MAX_LENGTH)  private Integer sequence; 

If it's an integer which one is proper for domain validation?
Can anybody explain me what is the difference between them?

Thanks.

like image 481
JOHND Avatar asked Jun 25 '12 12:06

JOHND


People also ask

What is min value and max value?

The minimum is the smallest value in the data set. The maximum is the largest value in the data set.

What is max value of integer in Java?

The int type in Java can be used to represent any whole number from -2147483648 to 2147483647. Why those numbers? Integers in Java are represented in 2's complement binary and each integer gets 32 bits of space.

What is @valid in Java?

The Java Bean Validation's @Valid constraint annotation makes sure that when an object is validated, the validation recurses to all fields that are annotated with @Valid . This makes it really easy to perform the usually complex task of validating entire object graphs.


2 Answers

@Min and @Max are used for validating numeric fields which could be String(representing number), int, short, byte etc and their respective primitive wrappers.

@Size is used to check the length constraints on the fields.

As per documentation @Size supports String, Collection, Map and arrays while @Min and @Max supports primitives and their wrappers. See the documentation.

like image 74
Sunil Chavan Avatar answered Oct 06 '22 10:10

Sunil Chavan


package com.mycompany;  import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size;  public class Car {      @NotNull     private String manufacturer;      @NotNull     @Size(min = 2, max = 14)     private String licensePlate;      @Min(2)     private int seatCount;      public Car(String manufacturer, String licencePlate, int seatCount) {         this.manufacturer = manufacturer;         this.licensePlate = licencePlate;         this.seatCount = seatCount;     }      //getters and setters ... } 

@NotNull, @Size and @Min are so-called constraint annotations, that we use to declare constraints, which shall be applied to the fields of a Car instance:

manufacturer shall never be null

licensePlate shall never be null and must be between 2 and 14 characters long

seatCount shall be at least 2.

like image 22
Rahul Agrawal Avatar answered Oct 06 '22 12:10

Rahul Agrawal