天天看點

@validate校驗中的@NotEmpty、@NotBlank、@NotNull差別

1、引入的包:jakarta.validation-api-2.0.2.jar

@validate校驗中的@NotEmpty、@NotBlank、@NotNull差別

2、直接看源碼上的注釋

@NotEmpty
/**
 * The annotated element must not be {@code null} nor empty.
 * <p>
 * Supported types are:
 * <ul>
 * <li>{@code CharSequence} (length of character sequence is evaluated)</li>
 * <li>{@code Collection} (collection size is evaluated)</li>
 * <li>{@code Map} (map size is evaluated)</li>
 * <li>Array (array length is evaluated)</li>
 * </ul>
 *  * @author Emmanuel Bernard
 * @author Hardy Ferentschik
 *  * @since 2.0
 */
@Documented
@Constraint(validatedBy = { })
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })
@Retention(RUNTIME)
@Repeatable(List.class)
public @interface NotEmpty {
	...
}
           
解釋
  • 此注解元素校驗必須不為null且不為空
  • 可以修飾的資料類型:
  • CharSequence(字元串)
  • Collection(集合)
  • Map(鍵值對)
  • Array(數組)
@NotBlank
/**
 * The annotated element must not be {@code null} and must contain at least one
 * non-whitespace character. Accepts {@code CharSequence}.
 *
 * @author Hardy Ferentschik
 * @since 2.0
 *
 * @see Character#isWhitespace(char)
 */
@Documented
@Constraint(validatedBy = { })
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })
@Retention(RUNTIME)
@Repeatable(List.class)
public @interface NotBlank {
	...
}
           
解釋
  • 此注解元素校驗必須不為null且必須包含一個不為空的字元串
  • 隻可以修飾的資料類型:CharSequence(字元串)
@NotNull
/**
 * The annotated element must not be {@code null}.
 * Accepts any type.
 *
 * @author Emmanuel Bernard
 */
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })
@Retention(RUNTIME)
@Repeatable(List.class)
@Documented
@Constraint(validatedBy = { })
public @interface NotNull {
	...
}
           
解釋
  • 此注解元素校驗必須不為null
  • 接受任意類型的資料

3、用法示例

/**
     * 員工ID
     */
    @NotEmpty(message = "員工id不能為空")
    private List<Integer> empIdList;


    /**
     * 客戶id
     */
    @NotBlank(message = "公司名稱不能為空")
    private String companyName;

    /**
     * 組織id
     */
    @NotNull(message = "組織ID不能為空")
    private String orgId;