简单类与带继承的类之间的映射

huangapple 未分类评论46阅读模式
英文:

Mapping between simple class and class with inheritance

问题

我有两个类似的类:

public class FileDto {
  private String name;
  private Integer size;
  private FileType fileType;
}

第二个类是:

public class File extends AbstractFile {
  private String name;
  private Integer size;
}

其中

public class AbstractFile {
  private FileConfiguration fileConfiguration;
}

而且 FileConfigurationFileType

public class FileConfiguration {
  FileType fileType;
}

现在我需要使用 MapStruct 编写三个映射器:

第一个很简单,正常工作 - 从 File 映射到 FileDto

@Mapping(target = "fileType", source = "fileConfiguration.fileType")
FileDto fromEntityToDto(final File entity);

第二个是从 FileDto 映射到 File。我想尝试一些类似的东西:

@Mapping(target = "fileConfiguration.fileType", source = "fileType")
File fromDtoToEntity(final FileDto dto);

但是它给我一个错误:

error: incompatible types: FileConfigurationBuilder cannot be converted to FileConfiguration
target.setFileConfiguration(FileConfiguration.builder());

第三个是:

@Mapping(target = "fileConfiguration.fileType", source = "fileType")
File updateEntity(final FileDto dto, @MappingTarget final File target);

你能告诉我如何在 @Mapping 注解中使用属性 target 吗?或者是否有其他方法?

英文:

I have two classes like:

public class FileDto {
  private String name;
  private Integer size;
  private FileType fileType;
}

The second one is:

public class File extends AbstractFile {
  private String name;
  private Integer size;
}

Where

public class AbstractFile {
private FileConfiguration fileConfiguration;
}

And FileConfiguration has FileType:

public class FileConfiguration {
FileType fileType
}

Now I need to write three mappers using MapStruct:

The first one is easy and works fine - mapping from File to FileDto:

@Mapping(target = "fileType", source = "fileConfiguration.fileType")
  FileDto fromEntityToDto(final File entity);

The second one is from FileDto to File. I would like to try something like:

  @Mapping(target = "fileConfiguration.fileType", source = "fileType")
  File fromDtoToEntity(final FileDto dto);

But it give me an error:

error: incompatible types: FileConfigurationBuilder cannot be converted to FileConfiguration
            target.setFileConfiguration( FileConfiguration.builder() );

And the third is:

  @Mapping(target = "fileConfiguration.fileType", source = "fileType")
  File updateEntity(final FileDto dto, @MappingTarget final File target);

Could you tell me how can I put property target in @Mapping annotation? Or is there any other way?

huangapple
  • 本文由 发表于 2020年7月23日 22:36:20
  • 转载请务必保留本文链接:https://java.coder-hub.com/63056808.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定