It sounds like your validation annotations @Email and @NonNull aren't being enforced when saving a @Document entity in MongoDB. Here are a few things to check:
pom.xml
:<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
This ensures that Hibernate Validator (Jakarta Bean Validation) is available.
Enable Validation in MongoDB Configuration
Spring Data MongoDB requires a ValidatingMongoEventListener to trigger validation before persisting documents:
@Configuration
@EnableMongoRepositories("your.package.repository")
public class MongoConfig {
@Bean
public ValidatingMongoEventListener validatingMongoEventListener(LocalValidatorFactoryBean factory) {
return new ValidatingMongoEventListener(factory);
}
}
This ensures that validation is applied when saving entities.
Use @Valid in Service or Controller Layer
If you're saving the entity manually, ensure that validation is triggered by using @Valid
:
public void saveUser(@Valid User user) { userRepository.save(user); }
If you're using a REST controller, annotate the request body:
@PostMapping("/users") public ResponseEntity createUser(@RequestBody @Valid User user) { userRepository.save(user); return ResponseEntity.ok("User saved successfully"); }
Check MongoDB Schema Validation
MongoDB allows schema validation using JSON Schema. If validation isn't working at the application level, you can enforce it at the database level.
If you've already done all this and validation still isn't triggering, let me know what errors (or lack thereof) you're seeing! We can troubleshoot further.