2

Does Spring Data JDBC validate entities while persisting - as Spring Data JPA does with the help of hibernate?

I have this scenario:

  • Entity (more or less a copy of the actual database table)
  • EntityDto (Data Transfer Object) with validation constraints such as @NotEmpty, @Min(5) etc
  • Web Layer (Spring MVC) where the DTO things get validated by spring stuff.

Given this structure and assuming that Spring Data JDBC does no validation - I don´t need other annotations in the entities than @Id do I?

Jens Schauder
  • 77,657
  • 34
  • 181
  • 348
Thomas Lang
  • 1,285
  • 17
  • 35

1 Answers1

3

Spring Data JDBC does no validation.

It also won't in the future, because validation is an orthogonal concern to persistence.

And yes, in the described case an @Id annotation might be all that you need. Although I'd recommend to have a column using @Version to enable optimistic locking.

I'm not a big fan of Bean Validation. Validation should happen in the constructor so that it is not possible to create an invalid object in the first place. This is supported by Spring Data JDBC since it supports non-trivial constructors.

Jens Schauder
  • 77,657
  • 34
  • 181
  • 348
  • I like the idea of validation done in the constructor too. In most of my cases i have a web form where i´m binding the dto via thymeleaf/Spring Mvc to html input fields. When i post this form back to the server via http, Spring Mvc constructs the model (via standard (no args) constructor) and sets the values by setters back to a dto (as far as i can tell). Would be cool if Spring Mvc might call overloaded constructors. Do you know if this might already happen by accident? – Thomas Lang Jun 16 '20 at 07:55
  • 1
    It has been to long that I used Spring MVC but I would expect it to use non-default constructors since Spring Frameworks dependency injection supports that as well. – Jens Schauder Jun 16 '20 at 08:00