MapStruct:如何映射到现有目标?

Den*_*lot 1 java mapstruct

我在更新实体的服务中有一个方法。它接受具有更新实体的数据的对象。Dto 对象的字段比实体少,但字段具有相同的名称。

通过传递现有的目标对象,是否可以将 mapstruct 用于该例行工作?

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)
  }
}
Run Code Online (Sandbox Code Playgroud)

jcc*_*ero 6

是的,您需要做的就是Mapper用一个update方法定义一个,例如:


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

@Mapper
public interface EntityMapper {
  void update(@MappingTarget Entity entity, UpdateEntity updateEntity);
}
Run Code Online (Sandbox Code Playgroud)

请查看相关文档

默认情况下,Mapstruct 会将源对象中的每个匹配属性映射到目标对象。