3

I have a Mongodb repository that is working fine:

@RepositoryRestResource(collectionResourceRel = "audits", path = "audits")
public interface AuditRepository extends MongoRepository<Audit, String> {
}

I have a bean, Audit that is:

@Data
@Document
@JsonIgnoreProperties(ignoreUnknown = true)
@Validated
public class Audit {
    @Id private String id;

    @NotNull
    private Date start;

    @NotNull
    private Date end;
}

I'm using Lombok for getters/setters.

I expect the Repository to validate the Audit bean, but it saves an audit bean with null in the start and end date.

I added this to the build.gradle:

compile("org.springframework.boot:spring-boot-starter-validation")

How do I tell the REST service to use validation? I don't see anything in RepositoryRestConfiguration that will turn it on...

mikeb
  • 10,578
  • 7
  • 62
  • 120

1 Answers1

6

You must import validations libs:

maven

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>5.4.2.Final</version>
</dependency>

or gradle

compile group: 'org.hibernate', name: 'hibernate-validator', version: '5.4.2.Final'

and you must configure two beans:

@Bean
public LocalValidatorFactoryBean localValidatorFactoryBean() {
    return new LocalValidatorFactoryBean();
}

@Bean
public ValidatingMongoEventListener validatingMongoEventListener(LocalValidatorFactoryBean lfb) {
    return new ValidatingMongoEventListener(lfb);
}
mikeb
  • 10,578
  • 7
  • 62
  • 120
Jialzate
  • 315
  • 1
  • 6
  • So I updated the Hibernate version (Hibernate validator 6 does not work here) and fixed your code snippet and marked it as correct – mikeb Jan 13 '18 at 19:36
  • 1
    In 2021 if you add the dependency it works with NotNull but not NotBlank (in which case it always fails). The rest of the answer looks about right though I copied my working code from https://stackoverflow.com/questions/42292359/spring-data-mongodb-not-null-annotation-like-spring-data-jpa – Rob Pitt Jan 03 '21 at 18:23