0

I'm building a Spring Boot 3.4.6 application using MongoDB and encountering an issue where @NonNull and @Email annotations are not triggering validation errors/exceptions even though I am using @Valid @RequestBody in the Controller. The only validation that is working is @Indexed (unique = true)

(Yess, @NonNull and @Email are 2 completely different annotations...)

I have tried:

  • Rebuilding my entire project (mvn clean build)
  • Checking for the required dependencies
  • Confirmed all annotations are from jakarta.validation.*, not javax.validation.* (for @Email annotation)
  • Sending clear invalid inputs using Postman

Yet, no validation error is triggered, and the user still gets created.

Here’s my setup:

User.java Entity Class

package com.sathwikhbhat.journalApp.entity;

import jakarta.validation.constraints.Email;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import org.bson.types.ObjectId;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.Document;

import java.util.ArrayList;
import java.util.List;

@Data
@NoArgsConstructor
@AllArgsConstructor
@Document(collection = "users")
public class User {
    @Id
    private ObjectId id;
    @Indexed(unique = true)
    @NonNull
    private String userName;
    @NonNull
    @Indexed(unique = true)
    @Email
    private String email;
    private boolean sentimentAnalysis;
    @NonNull
    private String password;
    @DBRef
    private List<JournalEntry> journalEntries = new ArrayList<>();
    private List<String> roles;
}

PublicController.java Controller Class

package com.sathwikhbhat.journalApp.controller;

import com.sathwikhbhat.journalApp.entity.User;
import com.sathwikhbhat.journalApp.service.UserService;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("/public")
public class PublicController {

    @Autowired
    private UserService userService;

    @PostMapping("createUser")
    public ResponseEntity<?> createUser(@Valid @RequestBody User user) {
        try {
            userService.saveNewUser(user);
            log.info("User created successfully: {}", user.getUserName());
            return new ResponseEntity<>(HttpStatus.CREATED);
        } catch (DuplicateKeyException e) {
            log.error(e.getMessage());
            return new ResponseEntity<>("Username already exists: ", HttpStatus.CONFLICT);
        } catch (Exception e) {
            log.error(e.getMessage());
            return new ResponseEntity<>("Internal server error: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}

Any insights or suggestions would be greatly appreciated!

7
  • Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. Commented Jun 17 at 6:49
  • Do validations work for you in any other controller method in that project? Maybe the issue is not specific to MongoDB entities Commented Jun 17 at 7:06
  • @AlexandruSeverin Nope, it doesn't work for any other controller methods in this project. It's getting quite frustrating... Commented Jun 17 at 7:21
  • 1
    @NonNull is from Lombok and doesn't do anything for validation only object construction. Wild guess you thought it would be a good idea to just add validation-api as a dependency and expected all to work. Instead add spring-boot-starter-validation and ditch the validation-api dependency. Commented Jun 17 at 7:43
  • 1
    Add spring-boot-starter-validation as that will pull in the correct and compatible dependencies. If you use the wrong mix of versions between API and the hibernate-validator it won't work. Commented Jun 17 at 9:22

1 Answer 1

3

You mentioned that annotations NonNull and Email do not work.

  • NonNull - Is not a a validation annotation. The annotation you are looking for is NotNull (from jakarta.validation.constraints)

  • Email - Is very permissive and email which you consider invalid may be considered valid by the annotation (see javax.validation.constraints.Email matching invalid email address for details). You can add regex parameter to indicate what pattern you want to use to validate emails

Also, note that as indicated by @M. Deinum in comments, if you imported only validation-api in your project you have access to the annotations but there may not be a validator implementation used to validate them. Check if you have a dependency used to validate the annotations, such as spring-boot-starter-validation

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, Alexandru. I just forgot how @NonNull works and ended up messing up this validation. And yes, @Email works fine after I added spring-boot-starter-validation. The jakarta.validation-api and hibernate-validator dependencies I added earlier weren’t the right ones...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.