liveBook · Manning

@patchmapping

As explained in Spring in Action, Sixth Edition

@PatchMapping is a Spring MVC annotation that maps HTTP PATCH requests to a controller method.

@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

How Spring in Action, Sixth Edition covers it

How deep it goes
Explains annotation selection and manual non-null field merging, but stops short of detailing alternative patching approaches.
Examples
Uses an order address update and a TacoOrder handler that conditionally copies supplied properties.
What you can do after
Build partial order updates by annotating a Spring MVC handler and applying only supplied fields.
How it connects
Connects partial updates with HTTP PATCH, PUT, @PutMapping, request bodies, controller methods, and repositories.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Spring in Action, Sixth Edition. The section links point to the parts of the book it draws on.