79670326

Date: 2025-06-18 09:12:52
Score: 0.5
Natty:
Report link

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:

  1. Ensure Spring Boot Validation Dependency
    Spring Boot doesn't include validation by default. You need to add this dependency in your pom.xml:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>
    1. This ensures that Hibernate Validator (Jakarta Bean Validation) is available.

    2. 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);
        }
    }
    
    1. This ensures that validation is applied when saving entities.

    2. Use @Valid in Service or Controller Layer
      If you're saving the entity manually, ensure that validation is triggered by using @Valid:

    3. public void saveUser(@Valid User user) { userRepository.save(user); }

    4. If you're using a REST controller, annotate the request body:

    5. @PostMapping("/users") public ResponseEntity createUser(@RequestBody @Valid User user) { userRepository.save(user); return ResponseEntity.ok("User saved successfully"); }

    6. 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.

Reasons:
  • Long answer (-1):
  • Has code block (-0.5):
  • User mentioned (1): @Email
  • User mentioned (0): @NonNull
  • User mentioned (0): @Document
  • User mentioned (0): @Valid
  • User mentioned (0): @Valid
  • Low reputation (1):
Posted by: Akash Singhal