How to enable Spring Bean Validation before persisting but ignore for HTTP request

abhaybhatia :

This is my scenario

class B {
   @NotNull 
   String x;
}

class A {
    @Valid
    B b;

    @NotNull
    String y;
} 

Now my Http POST request gets an object of class A as the payload. String y should be validated in the incoming HTTP request (and also validated before persisting to DB). However String x should NOT be validated in the incoming HTTP request (and only validated before persisting to DB) since String x will be null in the request and its value will be set by the business logic before the full class A object is persisted.

Is there any way to accomplish this ?

buræquete :

You can utilize validation groups if you can edit these objects;

class B {
    @NotNull(groups = Ignored.class)
    String x;
}

class A {
    @Valid
    B b;

    @NotNull
    String y;
} 

Where Ignored is;

import javax.validation.groups.Default;

public interface Ignored extends Default {
}

If your controller does not define this group, any annotation under it will be ignored, hence your requirement will be fulfilled, validation of B.x will be ignored in the request, but other fields of A will be validated. But I am not 100% sure that the validation will be applied in db side, can you try it?

Otherwise you can try to do;

@RestController
public class Controller {

    @PostMapping("/etc")
    ResponseEntity<String> addA(@RequestBody A a) { //disabled validation here
        B tempB = a.getB();
        a.setB(null);
        validateA(a);
        a.setB(tempB);
        // continue logic
    }
}

where validateA() is;

import org.springframework.validation.annotation.Validated;

@Validated
public class Validator {

    public void validateA(@Valid A a) {
        // nothing here
    }
}

Which is an ugly solution, but a solution nonetheless...

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=147214&siteId=1