Java / MapStruct Java Interview questions part 2
When should you use the @MappingTarget parameter?
Use @MappingTarget whenever you need to update fields on an object that already exists, rather than allocate a new one. The classic case is applying a PATCH/update DTO onto a persisted JPA entity that's already been loaded from the database in the same transaction.
@Mapping(target = "id", ignore = true) void updateFromDto(UserUpdateDto dto, @MappingTarget User user);
It's also useful when a caller already owns a mutable object (for example, a reusable buffer or a builder-style object) and you want to avoid the allocation cost of creating a new instance on every call. Any property in the DTO not represented (or explicitly ignored) still follows normal mapping rules, so unrelated identity fields like id are usually excluded with ignore = true to prevent accidental overwrites.
More Related questions...