24

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)
  }
}
Dennis Gloss
  • 2,307
  • 4
  • 21
  • 27
  • Please, provide a compilable code first. – Nikolas Charalambidis Nov 10 '20 at 11:45
  • @NikolasCharalambidis it would be easier to copy and paste, but nobody should do that from a question) The field names doesn't matter here. And all the java syntax with access modifiers and return types would make it messier I believe. It is a question about java, though) – Dennis Gloss Nov 10 '20 at 11:55
  • You might be surprized that most of the people copy+paste the question code and try to find out a solution in the ID. At least the class and method definitions would be complete. Take a look at here: [How to create a Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example). – Nikolas Charalambidis Nov 10 '20 at 12:37

1 Answers1

50

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.

jccampanero
  • 50,989
  • 3
  • 20
  • 49