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
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 Summary
Modifier and TypeMethodDescriptiontoEntity
(ProductRequest dto) Creates a newProduct
from an incoming request.toResponse
(Product entity) Creates aProductResponse
DTO suitable for API responses.void
updateEntity
(Product target, ProductRequest source) Updates an existingProduct
in-place from aProductRequest
.
-
Method Details
-
toEntity
Creates a newProduct
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 fromdto
-
toResponse
Creates aProductResponse
DTO suitable for API responses.- Parameters:
entity
- a managedProduct
entity (typically loaded or just persisted)- Returns:
- a value DTO reflecting the entity's current state
-
updateEntity
Updates an existingProduct
in-place from aProductRequest
. Fields that arenull
insource
are 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
-