简体   繁体   中英

issue with Java bean validation

I am a newbie and I am working with java bean validations.

I have a java bean class as given below with a null and size constraint.

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class Employee {
@NotNull
private int id;  
@NotNull
@Size(min=4, max=9)
private String name;  
public Employee(){}       
public void setId(int id){this.id=id;}  
public int getId(){return id;}  
public void setName(String name){this.name=name;}  
public String getName(){return name;}     
}

and I have a main class as below

public class Test {

public static void main(String[] args) {
    Employee e=new Employee();
      e.setId(0);
      System.out.println(e.getId());
    e.setName("abc");  

    System.out.println(e.getName()); 
    }}

This is expected to throw error when I pass name with length less than 4. But this class is executing successfully for all the values I pass. Let me know what I am missing here.

Thanks in advance.

Example code

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class Employee {
@NotNull
private int id;  
@NotNull
@Size(min=4, max=9, message="length error")
private String name;  
public Employee(){}       
public void setId(int id){this.id=id;}  
public int getId(){return id;}  
public void setName(String name){this.name=name;}  
public String getName(){return name;}   

main class:

public class Test {
    public static void main(String[] args) {
        Employee e = new Employee();
        e.setId(0);
        e.setName("abc");
        ValidatorFactory v = Validation.buildDefaultValidatorFactory();
        Validator validator = v.getValidator();
        Set<ConstraintViolation<Employee>> set = validator.validate(e);
        for (ConstraintViolation<Employee> constraintViolation : set) {
            System.out.println(constraintViolation.getMessage());
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM