Spring data mongoDb not null annotation like Spring data Jpa

Mehrish Yousuf picture Mehrish Yousuf · Feb 17, 2017 · Viewed 8.2k times · Source

Like spring-data-jpa have @NotNull annotation what can be used for this in spring-data-mongodb.?

Answer

Naveen Kumar picture Naveen Kumar · Mar 12, 2017

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").