MapStruct: How to map to existing target?

Viewed 11696

I have a method in a service that updates an entity. It accepts object that has the data to update the entity. Dto object has less fields than entity but the fields have the same names.

Could it be possible to use mapstruct for that routine job by passing an existing target object?

class Entity {
  id
  name
  date
  country
  by
  ... //hell of the fields
}
class UpdateEntity {
  name
  country
  ... //less but still a lot
}

class EntityService {
  update(UpdateEntity u) {
    Entity e = // get from storage
    mapstructMapper.mapFromTo(u, e)
  }
}
1 Answers

Yes, all you need to do is define a Mapper with an update method, something like:


import org.mapstruct.Mapper;
import org.mapstruct.MappingTarget;

@Mapper
public interface EntityMapper {
  void update(@MappingTarget Entity entity, UpdateEntity updateEntity);
}

Please, review the relevant documentation.

By default, Mapstruct will map every matching property in the source object to the target one.

Related