Spring boot starter data rest, @Notnull constraint not working

spring boot custom validator
spring boot validate request body
valid annotation not working
spring boot unique constraint validation
how to use notnull spring boot
notblank not working spring boot
spring validator example
spring data rest validation

I am trying to add @NotNull constraint into my Person object but I still can @POST a new Person with a null email. I am using Spring boot rest with MongoDB.

Entity class:

import javax.validation.constraints.NotNull;

public class Person {
    @Id 
    private String id;
    private String username;
    private String password;
    @NotNull // <-- Not working
    private String email;
    // getters & setters
}

Repository class:

@RepositoryRestResource(collectionResourceRel = "people", path = "people")
public interface PersonRepository extends MongoRepository<Person, String> {
}

Application class:

@SpringBootApplication
public class TalentPoolApplication {
    public static void main(String[] args) {
        SpringApplication.run(TalentPoolApplication.class, args);
    }
}

pom.xml

...
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.4.0.BUILD-SNAPSHOT</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-mongodb</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-rest</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>
...

When I @POST a new object via Postman like:

{
  "username": "deadpool",
  "email": null
}

I still get STATUS 201 created with this payload:

{
    "username": "deadpool",
    "password": null,
    "email": null
     ....
     ....
}

I had the same problem, but just enabling validation didn't work for me, this did work with both JPA and MongoDb to save anyone else spending ages on this. Not only does this get validation working but I get a nice restful 400 error rather than the default 500.

Had to add this to my build.gradle dependencies

    compile('org.hibernate:hibernate-validator:4.2.0.Final')

and this config class

@Configuration
public class CustomRepositoryRestConfigurerAdapter extends RepositoryRestConfigurerAdapter {


   @Bean
   public Validator validator() {
       return new LocalValidatorFactoryBean();
   }

   @Override
   public void configureValidatingRepositoryEventListener(ValidatingRepositoryEventListener validatingListener) {
       validatingListener.addValidator("afterCreate", validator());
       validatingListener.addValidator("beforeCreate", validator());
       validatingListener.addValidator("afterSave", validator());
       validatingListener.addValidator("beforeSave", validator());
   }
}

json, I am trying to add @NotNull constraint into my Person object but I still can @​POST a new Person with a null email. I am using Spring boot rest with MongoDB. To quickly set up a working environment and test the behavior of the @NotNull, @NotEmpty, and @NotBlank constraints, first we need to add the required Maven dependencies. In this case, we'll use Hibernate Validator , the bean validation reference implementation, for validating our domain objects.


i found it better to make my own version of @NotNull annotation which validates empty string as well.

@Documented
@Constraint(validatedBy = NotEmptyValidator.class)
@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface NotEmpty {


    String message() default "{validator.notEmpty}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

}

public class NotEmptyValidator implements ConstraintValidator<NotEmpty, Object> {

    @Override
    public void initialize(NotEmpty notEmpty) { }

    @Override
    public boolean isValid(Object obj, ConstraintValidatorContext cxt) {
        return obj != null && !obj.toString().trim().equals("");
    }

}

Validation in Spring Boot, Learn how to validate domain objects in Spring Boot using Hibernate Difference Between @NotNull, @NotEmpty, and @NotBlank Constraints in Bean Validation artifactId >spring-boot-starter-data-jpa</ artifactId > we need to define an example JPA entity class, whose role will just be modeling users. Spring Boot Tutorials. Hands-on examples. - Basics of Spring Boot. Covers Spring Boot Starter Projects, Spring Initializr, Creating REST Services, Unit and Integration tests, Profiles, Spring Boot Data JPA, Actuator and Security


You can either use the following code for validating

@Configuration
@Import(value = MongoAutoConfiguration.class)
public class DatabaseConfiguration extends AbstractMongoConfiguration 
{

  @Resource
  private Mongo mongo;

  @Resource
  private MongoProperties mongoProperties;

  @Bean
  public ValidatingMongoEventListener validatingMongoEventListener() {
    return new ValidatingMongoEventListener(validator());
  }

  @Bean
  public LocalValidatorFactoryBean validator() {
    return new LocalValidatorFactoryBean();
  }

  @Override
  protected String getDatabaseName() {
    return mongoProperties.getDatabase();
  }

  @Override
  public Mongo mongo() throws Exception {
    return mongo;
  }

}

Hibernate @NotNull vs @Column(nullable = false), artifactId >spring-boot-starter-data-jpa</ artifactId > Surprisingly, Hibernate automatically adds the not null constraint to the price In this article, we've described how the @NotNull and @Column(nullable – false) annotations work. HttpClient 4 Tutorial · REST with Spring Tutorial · Spring Persistence  Therefore, when Spring Boot validates the class instance, the constrained fields must be not null and their trimmed length must be greater than zero. Additionally, Bean Validation provides many other handy constraints besides @NotBlank. This allows us to apply and combine different validation rules to the constrained classes.


Normally, the @RestRepository will resolve into a controller than handles validation by itself, except if you Override the default behavior or it by including some @HandleBeforeSave, @HandleBeforeCreate, ... into your code.

A solution is to remove the @HandleBeforeSave, @HandleBeforeCreate, ... and then spring will handle the validation again.

Or if you want to keep them, you can provide a handler for any object validation like this:

@Component
@RepositoryEventHandler
public class EntityRepositoryEventHandler {

    @Autowired
    private Validator validator;

    @HandleBeforeSave
    @HandleBeforeCreate
    public void validate(Object o) {
        Set<ConstraintViolation<Object>> violations = this.validator.validate(o);

        if (!violations.isEmpty()) {
            ConstraintViolation<Object> violation = violations.iterator().next();

            // do whatever your want here as you got a constraint violation !

            throw new RuntimeException();
        }
    }
}

How to use Java Bean Validation in Spring Boot, Validation is performed by applying “constraints” on data items. For example, you can use it to validate REST API calls. The second option is to add the “​Spring-boot-starter-validation” dependency @NotNull: As the name implies, this annotation indicates that the annotated element should not be null. @EnableAutoConfiguration: Tells Spring Boot to start adding beans based on classpath settings, other beans, and various property settings. For example, if spring-webmvc is on the classpath, this annotation flags the application as a web application and activates key behaviors, such as setting up a DispatcherServlet .


Getting Started, can also use Gradle. It also shows values of com.example and validating-form-​input as the Group and Artifact, respectively. You will use those values throughout the rest of this sample. <artifactId>spring-boot-starter-thymeleaf</​artifactId> </dependency> <dependency> NotNull; import javax.validation.​constraints.Size  If for any reason we want to disable Bean Validation in our Spring Data repositories, we can set the Spring Boot property spring.jpa.properties.javax.persistence.validation.mode to none. Implementing A Custom Validator. If the available constraint annotations do not suffice for our use cases, we might want to create one ourselves.


All You Need To Know About Bean Validation With Spring Boot, This article is accompanied by a working code example on GitHub. implementation('org.springframework.boot:spring-boot-starter-validation') Very basically, Bean Validation works by defining constraints to the Here's the REST controller that takes an Input object in the request body and validates it:. To set up a Spring project with bean validation, you don’t really need anything specific except the core framework. But since I’ll be using it in a web application/REST API, I’ll add a few dependencies anyways, like HSQLDB, JPA, Lombok and Web. To do this, I’ll use the Spring Initializr to get my project.


Spring Validation for RESTful Services: With Examples , Data validation is not a new topic in web application development. int id; @​Size(max = 100) private String name; @NotNull private Boolean active; @NotNull <artifactId>spring-boot-starter-validation</artifactId> </dependency> The problem is that now we have to add constraint annotations directly to  Here we've added validation constraints that verify if an email is not provided at all, or provided, but not following the standard email address style. To show custom and locale-specific message, we can provide a placeholder as mentioned for the @NotEmpty annotation.