Search code examples
javaspring-boothibernateapijavax.validation

Executing specific group of javax validations


In my application I have an endpoint, that gets a JSON of this Object, which then calls calculateSomething() to return the number as a http response. I'm validating those values with javax.validation. Now is there a possible way for me, to specify how the object of the class Example is being validated or what values of this object will be validated in this one specific endpoint (I have multiple endpoints)? In this case for example, that if this endpoint gets called, that only one, two and three will be validated, because those are the only values needed for calculateSomething().

class:

@Entity
@PrimaryKeyJoinColumn(name = "five")
 public class Example extends Foo {
 
    @ValidOne
    @Column
    private Integer one;

    @ValidTwo
    @Column
    private Integer two;

    @ValidThree
    @Column
    private Integer three;

    @ValidFour
    @Column
    private Integer four;

    @ValidFive
    @Column
    private Integer five;

    @Override
    public Integer calculateSomething() throws IllegalArgumentException{
        (one + two) * three
    } 
}

endpoint:

@PostMapping ("/calculateSomeNumber")
    public ResponseEntity calculateSomeNumber(@Valid @RequestBody Example example){
        return ResponseEntity.ok(example.calculateSomething());
    }

Solution

  • You can declare interfaces which can signify as Group names. Then while defining a validation constraint apply it to specific group. To only validate using a specific validation group, simply apply it to relevant controller method

    public interface ValidOne {
    }
    
    public interface ValidTwo {
    }
      
    public class SomeController {
        @PostMapping ("/calculateSomeNumber")
        public ResponseEntity calculateSomeNumber(@Validated({ValidOne.class}) @RequestBody Example example){
            return ResponseEntity.ok(example.calculateSomething());
        }
    ...
    
    @Entity
    @PrimaryKeyJoinColumn(name = "five")
     public class Example extends Foo {
     
        @Column
        @NotNull(groups = ValidOne.class)
        private Integer one;
    
        @Column
        @NotNull(groups = ValidTwo.class)
        private Integer two;
    
    ....