Spring Data MongoDB Validation
So let’s understand how we can validate the fields before inserting into mongo db. So after the previous blog about the spring data mongodb example, let’s continue understand how we can add the validate the fields before inserting into mongo db.
So in the User.java we need to add following:
@NotEmpty
@Indexed(unique = true)
@Field(FIELD_EMAIL_ADDRESS)
private String emailAddress;
There are multiple annotations for validation. For example:
- @NotEmpty annotation asserts that the annotated string, collection, map or array is not null or empty.
- @NotBlank annotation validates that the annotated string is not null or empty.The difference to NotEmpty is that trailing white spaces are getting ignored.
- @Length annotation validates that the string is between min and max included
- @NotNull – annotated element must not be null
After adding these annotations the validation will not work. So we need to add following beans into the applicationContext.xml
<bean id="validatingMongoEventListener" class="org.springframework.data.mongodb.core.mapping.event.ValidatingMongoEventListener"> <constructor-arg name="validator" ref="localValidatorFactoryBean"/> </bean> <bean id="localValidatorFactoryBean" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>
After this if we try to save the user entity we will get ConstraintViolationException
So we need to handle this exception:
try {
userDAO.save(user);
} catch (ConstraintViolationException e) {
//DataIsNotValidException is our custom exception
throw new DataIsNotValidException("Data is not valid" + e.getMessage());
}