Spring data mongoDb not null annotation like Spring data Jpa

前端 未结 1 1938
北恋
北恋 2021-01-04 07:46

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

相关标签:
1条回答
  • 2021-01-04 08:21

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

    0 讨论(0)
提交回复
热议问题