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?

Sazzadur Rahaman
  • 6,938
  • 1
  • 30
  • 52
Kevin Rave
  • 13,876
  • 35
  • 109
  • 173

4 Answers4

99

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

Affe
  • 47,174
  • 11
  • 83
  • 83
  • Does `@Size(min=1)` subsume `@NotNull`? e.g. http://grepcode.com/file/repo1.maven.org/maven2/javax.validation/validation-api/1.1.0.Final/javax/validation/constraints/Size.java – Ken Mar 07 '14 at 14:05
  • 3
    @SK9 comment from the javadoc on the file you linked: "null elements are considered valid." – Affe Mar 09 '14 at 04:59
  • It is not exact the same - such combination will not work for just blank characters while @NoteEmpty will. – Aleksander Lech Nov 05 '14 at 12:00
  • 1
    @aleksjej you are thinking of `@NotBlank`. the source of `@NotEmpty` is merely: `@NotNull @Size(min = 1) public @interface NotEmpty {` – Affe Nov 08 '14 at 00:27
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.

Jerome_B
  • 1,079
  • 8
  • 15
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:

Matthew Read
  • 1,365
  • 1
  • 30
  • 50
zhouji
  • 5,056
  • 1
  • 26
  • 26
  • @NotEmpty returns a valild list with o element – Tayab Hussain Aug 29 '18 at 17:37
  • @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. – zhouji Sep 12 '18 at 06:35
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;
Deep Nirmal
  • 1,141
  • 1
  • 15
  • 14