0

I'm new to MongoDB. I'm using Spring boot 2.1.3.RELEASE.

I want to perform validation on MongoDB documents (on message as per below code), currently, it saves documents even everything passed as null.

I have gone through a couple of answers like Spring data mongoDb not null annotation like Spring data Jpa

public class Comment {

  @NotBlank(message = "Comment's message can't be blank")
  private String message;
  
  @CreatedDate
  private Date createdDate;

  @CreatedBy
  private String createdBy;

}

Is there any way to achieve the same without using hibernate-validator dependency?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Devkinandan Chauhan
  • 1,785
  • 1
  • 17
  • 42
  • Does this answer your question? [How to I get Spring-Data-MongoDB to validate my objects?](https://stackoverflow.com/questions/22568962/how-to-i-get-spring-data-mongodb-to-validate-my-objects) – Valijon Aug 05 '20 at 08:31
  • no, it answers in the same way I've already mentioned in the question – Devkinandan Chauhan Aug 05 '20 at 08:33
  • I see. Take a look this: [onBeforeSave](https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/index.html#mongodb.mapping-usage.events) – Valijon Aug 05 '20 at 08:40

1 Answers1

0

i was with the same problem and found this question. Here is how i solved my problem in my application that uses Spingboot e MongoDB

this is the only dependency needed.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

The DTO class with the rigth imports

And in the controller i used @Validated from

import org.springframework.validation.annotation.Validated;

    @PostMapping
@ResponseStatus(HttpStatus.CREATED)
public ProdutoData inserirProduto(@RequestBody @Validated ProdutoForm produto){
    return produtoServico.salvar(produto);
}

I hope this can help someone.