Home > Enterprise >  How to avoid adding @Valid on each and every inner-class fields during the hibernate-validator?
How to avoid adding @Valid on each and every inner-class fields during the hibernate-validator?

Time:03-18

I am currently developing an application within that I am adding a few validations on an inner class such as @NotNull, @Min, @Max, etc.

To make the validations work I need to add the @Valid on each and every field which is making use of the inner class. Is there a way to avoid adding the @Valid on each and every object rather add some annotations on the Class so it can be applicable to all the fields within that class?

I am currently using the following library to achieve the validations:

<dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-hibernate-validator</artifactId>
</dependency>

I tried to add the @Validated on the class but seems like this annotation is not available in this maven dependency. Can someone please let me know what I need to change?

Following is a simple example that is working but I would like to remove @Valid that I have to add on each field. If I do not add @Valid then those inner classes won't be validated.

public class Book {
    @NotNull(message="Book ID cannot be NULL")
    private int bookId;

    @Valid
    private List<Author> author;

    @Valid
    private List<Publication> author;
}


public class Author {
    @NotNull(message="Author ID cannot be NULL")
    private int authorID;

    @NotNull(message="Author Name cannot be NULL")
    private String name;
}


public class Publication {
    @NotNull(message="Publication ID cannot be NULL")
    private int authorID;

    @NotNull(message="Publication Name cannot be NULL")
    private String name;
}

CodePudding user response:

There is no way to do what you want to do, except if you write your own Quarkus extension that will add the annotations at build time.

It will be some rather involved work, though, as you will need to add some bytecode transformation to add the annotations where you want them.

Also, you should add the @Valid annotations inside the List e.g. List<@Valid Publication> rather than at the field level. It's more optimized this way.

  • Related