@PatchMapping maps HTTP PATCH requests to a Spring MVC controller method. PATCH is useful when a client changes only part of an existing resource instead of replacing the complete resource. section 7.1.3
Partially updating an order
An order address can be updated without resending the complete order or its tacos. The handler loads the existing order, checks each incoming field, and applies only non-null values; omitted properties remain unchanged. section 7.1.3
Using @PatchMapping requires distinguishing request mapping from update behavior:
- Use @PatchMapping instead of @PutMapping to select HTTP PATCH requests. section 7.1.3
- Include the path variable and request body needed to identify the order and receive changed values. section 7.1.3
- Implement partial-update logic explicitly; the annotation does not automatically merge incoming data. section 7.1.3
@PatchMapping(path="/{orderId}", consumes="application/json")
public TacoOrder patchOrder(@PathVariable("orderId") Long orderId,
@RequestBody TacoOrder patch) {
TacoOrder order = repo.findById(orderId).get();
if (patch.getDeliveryName() != null) {
order.setDeliveryName(patch.getDeliveryName());
}
if (patch.getDeliveryStreet() != null) {
order.setDeliveryStreet(patch.getDeliveryStreet());
}
if (patch.getDeliveryCity() != null) {
order.setDeliveryCity(patch.getDeliveryCity());
}
if (patch.getDeliveryState() != null) {
order.setDeliveryState(patch.getDeliveryState());
}
if (patch.getDeliveryZip() != null) {
order.setDeliveryZip(patch.getDeliveryZip());
}
if (patch.getCcNumber() != null) {
order.setCcNumber(patch.getCcNumber());
}
if (patch.getCcExpiration() != null) {
order.setCcExpiration(patch.getCcExpiration());
}
if (patch.getCcCVV() != null) {
order.setCcCVV(patch.getCcCVV());
}
return repo.save(order);
}
A complete handler pattern shows loading an order and conditionally copying supplied fields before saving it. section 7.1.3
