I have defined two Spring boot REST resources
POST /customer
The above resource is for adding a customer with the below JSON as a request
{
"customerFirstName" : "John"
"customerLastName" : "Doe"
"customerAddress" : {
"addressLine1" : "22 XYZ Drive"
"addressLine1" : "22 suite"
"state" : "PY"
"country" : "Ind"
"zipCode" : "1235312"
}
}
Now I need to implement update the customer info, so the below resource is defined. The requirement is any information related to customers can be updated. So the Input JSON in case of an update is the same as in the case of add request. The only caveat the information that is not provided will not be updated. Only information that is provided will be updated.
PUT /customer/{customerId}
Question : I want to use Spring boot Bean request validation. However, the validation requirements are different for adding and updating resources, so not able to use the same Customer
domain model. However, the domain model in both cases is exactly the same so this is causing a code duplication. How can I avoid that or is it correct to move the validation outside and code.
Example : In the case of adding a customer it is mandatory to provide a customer address, so one can use annotation like @NotNull
. However, in the case of updating the customer, the customer address is not mandatory.
CodePudding user response:
You should be able to use validation groups and keep a single model class. Each constraint has groups
attribute that you can use to define a validation scheme. You can have a Create
group that you'll use only in the POST request and ignore in the PATCH one:
interface Create {}
class Customer {
@NotNull(groups = Create.class)
private String firstName;
@NotNull(groups = Create.class)
private String lastName;
//....
}
And then as you are using Spring you'd want to take a look at @Validated
annotation. This one allows you to define the particular groups you want to validate against:
@PostMapping("/customer")
public ResponseEntity<Customer> create(@RequestBody @Validated(Create.class) Customer customer) {
// do your thing
}
You can also check this part of the documentation to learn more about groups and their capabilities