J
J
Jake Taylor2021-11-02 17:29:39
Hibernate
Jake Taylor, 2021-11-02 17:29:39

Why doesn't Hibernate validate work?

As you know , in the controller, when passing the name of the argument in the request, which must be an Enum, there is a functionality for automatically converting this argument to one of the Enum's values.

Here is what I have registered in the controller FormatterRegistry:

@Override
public void addFormatters(FormatterRegistry registry) {
    registry.addConverter(new StringToColumnNameConverter());
}


Here is what it looks like StringToColumnNameConverterinside with Hibernate validation (@NotBlank):

public class StringToColumnNameConverter implements Converter<String, ColumnName> {
    @Override
    public ColumnName convert(@NotBlank(message = PropertyKey.VALIDATION_DATABASE_COLUMN_NAME_NOT_BLANK) String source) {
        return ColumnName.valueOf(source.toUpperCase());
    }
}


Move on. In the controller, a method is called that takes a column name ( columnName):

@GetMapping(params = ParameterName.SORT_BY)
    public Set<GiftCertificateDto> findAllSorted(@RequestParam(value = ParameterName.SORT_BY)
                                                 @NotEmpty(message = PropertyKey.VALIDATION_GIFT_CERTIFICATE_COLUMN_MANE_NOT_EMPTY)
                                                         Set<ColumnName> columnNames) {

        return service.findAllSorted(columnNames);
}


First Hibernate annotation
@NotEmpty(message = PropertyKey.VALIDATION_GIFT_CERTIFICATE_COLUMN_MANE_NOT_EMPTY)
works out with a bang. But if I pass a string containing only spaces of the form , then the second annotation @NotBlankinside StringToColumnNameConverterfor some reason does not work out. Why?

What I have tried:
- annotate @Validatedthe class StringToColumnNameConverter;
- annotate the class @Validatedmethod ; - added annotation :convert(...)StringToColumnNameConverter
StringToColumnNameConverter@Valid
public class StringToColumnNameConverter implements Converter<@Valid String, ColumnName>

- in the controller inside the Set, insert the annotation @Valid:
@GetMapping(params = ParameterName.SORT_BY)
    public Set<GiftCertificateDto> findAllSorted(@RequestParam(value = ParameterName.SORT_BY)
                                                 @NotEmpty(message = PropertyKey.VALIDATION_GIFT_CERTIFICATE_COLUMN_MANE_NOT_EMPTY)
                                                         Set<@Valid ColumnName> columnNames) {

        return service.findAllSorted(columnNames);
    }


The controller is annotated with @Validated.

For reference:@NotBlank - The annotated element must not be null and must contain at least one non-whitespace character. Accepts CharSequence.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question