Hibernate @NotEmpty annotation equivalent in Javax.package or alternative
Asked Answered
P

4

41

Is there a way to implement @NotEmpty hibernate validation without writing custom validation? javax.validation package does not contain this annotation. Only @NotNull. But it does not validate for Non-null but empty values. So I would like to see an alternative for @NotEmpty.

Using @Pattern? How?

Photocomposition answered 5/7, 2013 at 5:43 Comment(0)
T
101

NotEmpty is just a combination of @NotNull and @Size(min=1).

Tetchy answered 5/7, 2013 at 6:5 Comment(4)
Does @Size(min=1) subsume @NotNull? e.g. grepcode.com/file/repo1.maven.org/maven2/javax.validation/…Finesse
@SK9 comment from the javadoc on the file you linked: "null elements are considered valid."Tetchy
It is not exact the same - such combination will not work for just blank characters while @NoteEmpty will.Jockey
@aleksjej you are thinking of @NotBlank. the source of @NotEmpty is merely: @NotNull @Size(min = 1) public @interface NotEmpty {Tetchy
F
9

Please be aware that @NotEmpty will return valid for a List<> containing a null element.

Kind of bizarre in the case of a @QueryParam List<>

As say Affe, I did a custom annotation, itself annotated with @NotNull and @Size(min=1) with a custom validator that iterates the collection and positions a boolean flag only if the elements are not null.

Freezedry answered 29/7, 2016 at 12:45 Comment(0)
M
2

In the Hibernate @NotEmpty source code after Hibernate 6, it told us use the standard javax.validation.constraints.NotEmpty constraint instead:

/**
 * Asserts that the annotated string, collection, map or array is not {@code null} or empty.
 *
 * @author Emmanuel Bernard
 * @author Hardy Ferentschik
 *
 * @deprecated use the standard {@link javax.validation.constraints.NotEmpty} constraint instead
 */

See: https://github.com/hibernate/hibernate-validator/blob/6.0/engine/src/main/java/org/hibernate/validator/constraints/NotEmpty.java

This new annotation comes from Bean Validation 2.0 (JSR 380). See:

Matelda answered 7/3, 2018 at 4:3 Comment(2)
@NotEmpty returns a valild list with o elementHedda
@TayabHussain What @NotEmpty? Hibernate @NotEmpty or Bean Validation spec @NotEmpty? The Bean Validation spec @NotEmpty can validate string, collection, map or array too as the source code and Hibernate team point out.Matelda
C
1

For Hibernate it is deprecated in the newer version.
With the newer version of Javax validation it has @Empty

Use

import javax.validation.constraints.NotEmpty;

@NotEmpty
private List<Record> records;
Crosstree answered 24/3, 2019 at 9:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.