问题描述
像 spring-data-jpa 一样有 @NotNull 注释,在 spring-data-mongodb 中可以用什么来做这个.?
Like spring-data-jpa have @NotNull annotation what can be used for this in spring-data-mongodb.?
推荐答案
javax.validation.constraints.NotNull
本身可以与 spring-data-mongodb 一起使用.为此,您需要有以下人员.
javax.validation.constraints.NotNull
itself could be used with spring-data-mongodb. For this you need to have following in place.
在 pom.xml 中添加了 JSR-303 依赖项
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.3.4.Final</version>
</dependency>
声明适当的验证器和验证器事件监听器
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();
}
}
在 MongoDB POJO 中添加 @NotNull 注释
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;
}
使用此配置和实现,如果您使用空值持久化 User 对象,那么您将看到 javax.validation.ConstraintViolationException
With this configuration and implementation, if you persist User object with null values, then you will see failure with javax.validation.ConstraintViolationException
记住:如果使用 @SpringBootApplication
,请确保 Spring 可以扫描您的配置文件.否则,您可以使用 @ComponentScan("com.mypackage")
.
Remember: if using @SpringBootApplication
, make sure that Spring can scan your Configuration file. Otherwise, you may use @ComponentScan("com.mypackage")
.
这篇关于Spring data mongoDb 不是像 Spring data Jpa 这样的 null 注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!