目标属性的几个可能的源属性"address"


@Mapper(componentModel = "spring", injectionStrategy = InjectionStrategy.CONSTRUCTOR)
public abstract class FooMapper {
@Autowired
static AddressMapper addressMapper;
@Mapping(source = "entity.id", target = "id")
@Mapping(target = "address", qualifiedByName = "mappingAddress")
public abstract FooEntity dtoAndEntityToEntity(FooDto dto, FooEntity entity);

@Named("mappingAddress")
static AddressEntity mappingAddress(FooDto dto, FooEntity entity) {
if (Objects.nonNull(dto) && Objects.nonNull(dto.getAddress())) {
return addressMapper.dtoToEntity(dto.getAddress());
}
if (Objects.nonNull(entity)) {
return entity.getAddress();
}
return null;
}
}

我甚至想从dto的实体映射地址,如果dto为null,我应该使用实体信息,我使用了那个自定义方法,但我得到了错误:

Error:(27,41) java: Several possible source properties for target property "address".

错误很明显,错误的发生是因为实体和dto有地址属性,但我不想设置source,我希望它从实体或dto中扣除。

有什么办法可以避免这个错误吗?

我在您的解决方案中看到了几个问题。。是否需要映射目标(作为更新方法?(。然后你需要这样的方法参数。(请注意,在这些情况下,我个人认为结果无效(。

然后:如果您有选择冲突,则只需要qualifiedBy。因此,本质上,如果您有多个具有相同签名的方法可供MapStruct选择。

最后,你需要表明这是你正在考虑的整个对象。


@Mapper(componentModel = "spring", injectionStrategy = InjectionStrategy.CONSTRUCTOR)
public abstract class FooMapper {
//@Autowired not sure whether you should use a static field for this, perhaps you should inject it at the place where you are going to use the mapper.
// static AddressMapper addressMapper;
@Mapping(source = "entity.id", target = "dto.id")
@Mapping(target = "address", source = "dto" )
public abstract void dtoAndEntityToEntity(FooDto dto, @MappingTarget FooEntity entity);

// why was this method static? The mapper itself is already by design a singleton.
@Named("mappingAddress")
void mappingAddress(FooDto dto, @MappingTarget FooEntity entity) {
if (Objects.nonNull(dto) && Objects.nonNull(dto.getAddress())) {
addressMapper.dtoToEntity(dto.getAddress());
}
if (Objects.nonNull(entity)) {
entity.getAddress();
}
}
}

相关内容

  • 没有找到相关文章

最新更新