Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MapStruct: How to map to existing target?

Tags:

java

mapstruct

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)
  }
}
like image 338
Dennis Gloss Avatar asked Sep 01 '25 23:09

Dennis Gloss


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.

like image 161
jccampanero Avatar answered Sep 03 '25 14:09

jccampanero