Like spring-data-jpa have @NotNull annotation what can be used for this in spring-data-mongodb.?
Asked
Active
Viewed 1.6k times
1 Answers
35
javax.validation.constraints.NotNull
itself could be used with spring-data-mongodb. For this you need to have following in place.
JSR-303 dependencies added in your pom.xml
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.3.4.Final</version>
</dependency>
Declare appropriate validators and validator event listeners
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.core.mapping.event.ValidatingMongoEventListener;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
@Configuration
public class Configuration {
@Bean
public ValidatingMongoEventListener validatingMongoEventListener() {
return new ValidatingMongoEventListener(validator());
}
@Bean
public LocalValidatorFactoryBean validator() {
return new LocalValidatorFactoryBean();
}
}
Add @NotNull annotation in your MongoDB POJO
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import javax.validation.constraints.NotNull;
@Document(collection = "user_account")
public class User {
@Id
private String userId;
@NotNull(message = "User's first name must not be null")
private String firstName;
@NotNull(message = "User's last name must not be null")
private String lastName;
}
With this configuration and implementation, if you persist User object with null values, then you will see failure with javax.validation.ConstraintViolationException
Remember: if using @SpringBootApplication
, make sure that Spring can scan your Configuration file. Otherwise, you may use @ComponentScan("com.mypackage")
.

Marcos
- 39
- 10

Naveen Kumar
- 893
- 11
- 19
-
1Does the `userId` have to be annotated as `@NotNull` as well? – Tarun Kolla Jul 29 '19 at 18:13
-
you saved me. it is not so easy achieving this nativelly from mongodb. great – Salvatore Pannozzo Capodiferro Aug 22 '19 at 16:45