MapStruct:如何映射到现有目标?
MapStruct: How to map to existing target?
我在更新实体的服务中有一个方法。它接受具有更新实体数据的对象。 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)
}
}
您需要像这样创建自定义映射器:
您需要指定所有映射规则(即使 name/type 不同)
@Mapper
public interface EntityMapper {
@Mapping(target="name", source="name")
@Mapping(target="country", source="country")
//... other fileds
Entity entityToUpdateEntityMapper(UpdateEntity updateEntity );
}
2- 将生成实现,您可以将自定义映射器与自定义规则一起使用
是的,您需要做的就是用 update
方法定义一个 Mapper
,例如:
import org.mapstruct.Mapper;
import org.mapstruct.MappingTarget;
@Mapper
public interface EntityMapper {
void update(@MappingTarget Entity entity, UpdateEntity updateEntity);
}
请查看相关的 documentation。
默认情况下,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)
}
}
您需要像这样创建自定义映射器:
您需要指定所有映射规则(即使 name/type 不同)
@Mapper
public interface EntityMapper {
@Mapping(target="name", source="name")
@Mapping(target="country", source="country")
//... other fileds
Entity entityToUpdateEntityMapper(UpdateEntity updateEntity );
}
2- 将生成实现,您可以将自定义映射器与自定义规则一起使用
是的,您需要做的就是用 update
方法定义一个 Mapper
,例如:
import org.mapstruct.Mapper;
import org.mapstruct.MappingTarget;
@Mapper
public interface EntityMapper {
void update(@MappingTarget Entity entity, UpdateEntity updateEntity);
}
请查看相关的 documentation。
默认情况下,Mapstruct 会将源对象中的每个匹配 属性 映射到目标对象。