I've been searching for the simplest and best way to validate my entities before they are created/updated and after much googling, I couldn't find a clean/modern one.
Ideally, I would have loved to be able to use @Valid as follows:
import javax.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.rest.core.annotation.HandleBeforeCreate;
import org.springframework.data.rest.core.annotation.HandleBeforeSave;
import org.springframework.data.rest.core.annotation.RepositoryEventHandler;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
@Slf4j
@Validated
@Component
@RepositoryEventHandler
public class CustomerEventHandler {
// Triggered for POST
@HandleBeforeCreate
public void onBeforeCreate(@Valid Customer entity) {
log.info("Saving new entity {}", entity);
}
// Triggered for PUT / PATCH
@HandleBeforeSave
public void onBeforeSave(@Valid Customer entity) {
log.info("Saving new entity {}", entity);
}
}
The Customer entity being:
import javax.validation.constraints.NotBlank;
@Getter
@Setter
@ToString
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "customer")
public class Customer {
@NotBlank
private String firstname;
}
But it doesn't seem to work.
What's the modern, easy way to validate entities in Spring Data REST?
Note: I'm using Spring Boot
CodePudding user response:
I checked your pom.xml in linked GitHub project. You have just a dependency to validation annotations, but the proper way with Spring Boot is to use the spring-boot-starter-validation Dependency. The Spring Boot Starter Dependencies add the "magic" to your project, which triggers automatically the validation based on your annotations.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
I my German blog I have written an article about this topic:
https://agile-coding.blogspot.com/2020/11/validation-with-spring.html
CodePudding user response:
I want to suggest a few best practise that every developer, who starting as junior/beginner should be know. Don't put any Validation annotation in Entities, using them in DTO/Resource classes. and the best way to practise validation is that you can handler MethodArgumentNotValidation
exception in your own Spring Boot of Exception Handler class annotated that class @RestControllerAdvice
and create your own @interface
annotation instead of using more validation annotation.