像spring-data-jpa有@NotNull注释可以在spring-data-mongodb中使用它。
答案 0 :(得分:16)
String str; // The string is declared
str = "whatever" // The string is initialized
String string = "whatever" // The string is initialized and declared`
本身可以与spring-data-mongodb一起使用。为此,您需要有适当的跟进。
在您的pom.xml中添加了JSR-303依赖项
javax.validation.constraints.NotNull
声明适当的验证器和验证器事件侦听器
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.3.4.Final</version>
</dependency>
在MongoDB POJO中添加@NotNull注释
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();
}
}
使用此配置和实现,如果您使用空值保留User对象,那么您将看到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;
}