Interface ProductMapper


public interface ProductMapper
Maps between API-layer DTOs and the Product JPA entity.

How it works: MapStruct generates an implementation at build time (e.g. ProductMapperImpl). With componentModel="spring", the mapper is registered as a Spring bean and can be injected into controllers or services.

Design notes

  • toEntity is intended for create flows. The resulting entity has a null id.
  • toResponse is a read-side projection that keeps your HTTP contract decoupled from JPA.
  • updateEntity performs an in-place, partial update: null values in the source DTO are ignored (see NullValuePropertyMappingStrategy.IGNORE). This makes it safe for PATCH-like flows.

Examples


 // Create flow (Controller)
 @PostMapping("/products")
 ResponseEntity<ProductResponse> create(@Valid @RequestBody ProductRequest req) {
   Product entity = mapper.toEntity(req);
   Product saved = productService.create(entity);
   return ResponseEntity
      .created(URI.create("/products/" + saved.getId()))
      .body(mapper.toResponse(saved));
 }

 // Partial update (Service)
 public Product patch(Long id, ProductRequest req) {
   Product existing = getOrThrow(id);
   mapper.updateEntity(existing, req);  // nulls in req won't overwrite
   return repo.save(existing);
 }
 
Since:
1.0
  • Method Details

    • toEntity

      Product toEntity(ProductRequest dto)
      Creates a new Product from an incoming request.

      Intended for create flows; the returned entity has id == null and is ready to be persisted.

      Parameters:
      dto - validated request payload containing user-provided fields
      Returns:
      a new Product with fields copied from dto
    • toResponse

      ProductResponse toResponse(Product entity)
      Creates a ProductResponse DTO suitable for API responses.
      Parameters:
      entity - a managed Product entity (typically loaded or just persisted)
      Returns:
      a value DTO reflecting the entity's current state
    • updateEntity

      void updateEntity(Product target, ProductRequest source)
      Updates an existing Product in-place from a ProductRequest. Fields that are null in source are ignored and do not overwrite non-null values in target. This makes the method safe for PATCH-like flows as well as PUT flows where validation guarantees non-null fields.
      Parameters:
      target - the entity to mutate (usually loaded from the database)
      source - the incoming request containing new values