Package com.example.springrest.mappers
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
nullid. - 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);
}
API note: Mapping behavior is compile-time generated; if you add new fields to the entity/DTOs,
consider enabling MapStruct's unmappedTargetPolicy = ReportingPolicy.ERROR to catch omissions.
- Since:
- 1.0
-
Method Summary
Modifier and TypeMethodDescriptiontoEntity(ProductRequest dto) Creates a newProductfrom an incoming request.toResponse(Product entity) Creates aProductResponseDTO suitable for API responses.voidupdateEntity(Product target, ProductRequest source) Updates an existingProductin-place from aProductRequest.
-
Method Details
-
toEntity
Creates a newProductfrom an incoming request.Intended for create flows; the returned entity has
id == nulland is ready to be persisted.- Parameters:
dto- validated request payload containing user-provided fields- Returns:
- a new
Productwith fields copied fromdto
-
toResponse
Creates aProductResponseDTO suitable for API responses.- Parameters:
entity- a managedProductentity (typically loaded or just persisted)- Returns:
- a value DTO reflecting the entity's current state
-
updateEntity
Updates an existingProductin-place from aProductRequest. Fields that arenullinsourceare ignored and do not overwrite non-null values intarget. 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
-