使用Java Bean Validation API非空校验

1.在实体中添加@NotNull注解

先定义一个实体类

import javax.validation.constraints.NotNull;

public class User
    @NotNull
    private String name;
    @NotNull
    private String sex;
    @NotNull
    private String age;
}

2.创建验证器,验证实体类

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

public static void main(String[] args) {
     User user = getById(id);
     ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
     Validator validator = factory.getValidator();
     Set<ConstraintViolation<User>> violations = validator.validate(user);
     if (violations.isEmpty()) {
    	// entity is valid
	 } else {
	    // entity is invalid
	    for (ConstraintViolation<MyEntity> violation : violations) {
	        System.out.println(violation.getMessage());
	    }
	 }
}

其中**Set violations = validator.validate(user);**就是返回的为空字段的个数,如果size为0,证明该实体加了 @NotNull的字段全部验证通过

注意点
1.注意导包javax.validation

你可能感兴趣的:(java,开发语言,服务器)