abhaybhatia
abhaybhatia

Reputation: 629

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

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 ?

Upvotes: 2

Views: 1196

Answers (3)

buræquete
buræquete

Reputation: 14698

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...

Upvotes: 1

liuchu
liuchu

Reputation: 60

Actually it would not affect if "@Valid" annotation was not prefixed the arguments, @Jonathan explained it.

To enable validation before persist, it's work like this way:

@Repository
@Validated
public MyDao {
    public void insertA(@Valid A a){
        //logic here
    }

}

@Validated(org.springframework.validation.annotation.Validated) is the key to enable arguments validation. It works for me.

Upvotes: 1

Jonathan JOhx
Jonathan JOhx

Reputation: 5968

I think you missing add @Vaild annotation on parameter which will be validated in controller layer.

@RestController
public class AController {

    @PostMapping("/a")
    ResponseEntity<String> addA(@Valid @RequestBody A a) {
        // persisting the a entity 
        return ResponseEntity.ok("A is valid");
    }
}

Upvotes: 1

Related Questions