Java / MapStruct Java Interview questions part 2
What is the difference between returning a new object and using @MappingTarget?
A regular mapping method (TargetDto toDto(Source s)) always constructs a brand-new target instance and populates it from the source. Any existing state on a target you might have had beforehand is irrelevant - you get a fresh object every time.
A method that accepts a parameter annotated @MappingTarget instead updates an already-existing instance in place, leaving properties with no matching source value untouched rather than resetting them to defaults.
void updateEntity(Dto dto, @MappingTarget Entity entity);
This distinction matters most for partial updates - for example, a PATCH endpoint should only overwrite the fields present in the request, which is exactly what an @MappingTarget update method does, whereas a plain toEntity method would replace everything with a new object.
More Related questions...