Some helpful validations and utilities to be used in your Spring Boot application. Check the features list below.
Add the following dependency in your project to start using the features described below.
implementation 'io.github.manuelarte.spring:manuelarte-validation:{latest-version}'
This constraint can be used to check in a controller if the entity exists before executing the method
-
The constraint validations need to be executed, for example annotating your Controller with @Validated
-
The entity/document that is going to be checked needs to have a Repository.
@Validated
public class DocumentController {
@GetMapping(value = "/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<DocumentEntity> findOne(
@PathVariable @Exists(DocumentEntity.class) final String id) {
return ResponseEntity.ok(documentService.findOne(id));
}
}
@Repository
public interface DocumentEntityRepository extends CrudRepository<DocumentEntity, Long> {}
There are three groups added to be used in your dtos, New, Update, PartialUpdate, that can be used as validation groups.
Imagine that you have an entity that you want to allow to be created, updated and partially updated. By using validation groups, we can have the same dto for the different endpoints. Here is an example:
public class OneEntityDto {
@Null(groups = {New.class, PartialUpdate.class})
@NotNull(groups = Update.class)
private final Long id;
@NotEmpty(groups = {New.class, Update.class})
private final String firstName;
@NotEmpty(groups = {New.class, Update.class})
private final String lastName;
}
@Validated
public class OneEntityController {
@PostMapping(value = "/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<OneEntity> findOne(
@Validated({Default.class, New.class}) @RequestBody final OneEntity newEntity) {
return ResponseEntity.ok(entityService.save(newEntity));
}
}
As you can see, when posting new entities, the validation groups default and new will apply.
This constraint helps to validate two dates.
@FromAndToDate
public class EntityExample {
@FromDate
private final Date from;
@ToDate
private final Date to;
...
}
This constraint will check that the field from is lower than (or equal if the configuration of FromAndToDate annotation allows it) to the to parameter
@FromAndToDate
public void methodExample(Date from, Date to) {
...
}
The constraint will check that the parameters from and to match from is before than to. By default the constraint will check the 1st and 2nd parameters indexes. In case they are in a different index it should be set like this:
@FromAndToDate(paramIndexes={x,y})
where x and y are the indexes of the parameters to be checked.