可能这可能是一个非常简单的问题,但是在解决给定的问题时我很失落。

我有一个称为MediaResource的实体,它具有id,imageName等字段。另一方面,有MediaResourceDTO,它具有imageName,byte [] resourceFile等。

这个想法是从数据库中获取图像名称,并且在将MediaResourceDTO发送到客户端之前,我想将图像文件加载到MediaResourceDTO中。

我不知道如何从MapStruct实现这一目标。

我已经看到了@Before和@After的几个示例,但我不了解其用例。

这是我的源代码:
MediaResourceMapper

@Mapper(componentModel = "spring", uses = {VehicleMapper.class, })
public interface MediaResourceMapper {

    MediaResourceDTO mediaResourceToMediaResourceDTO(MediaResource mediaResource);

    List<MediaResourceDTO> mediaResourcesToMediaResourceDTOs(List<MediaResource> mediaResources);

    MediaResource mediaResourceDTOToMediaResource(MediaResourceDTO mediaResourceDTO);

    List<MediaResource> mediaResourceDTOsToMediaResources(List<MediaResourceDTO> mediaResourceDTOs);

    default MediaResource mediaResourceFromId(Long id) {
        if (id == null) {
            return null;
        }
        MediaResource mediaResource = new MediaResource();
        mediaResource.setId(id);
        return mediaResource;
    }
}


MediaResource实体

@Entity
@Table(name = "media_resource")
public class MediaResource implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "field_name")
    private String fieldName;

    @Column(name = "original_media_file_name")
    private String originalMediaFileName;

    @Column(name = "encrypted_media_file_name")
    private String encryptedMediaFileName;


    @Column(name = "resource_file_content_type", nullable = false)
    private String resourceFileContentType;

}


MediaResourceDTO

public class MediaResourceDTO implements Serializable {

    private Long id;

    private String fieldName;

    private String originalMediaFileName;

    private String encryptedMediaFileName;

    @NotNull
    @Size(max = 20000000)
    @Lob
    private byte[] resourceFile;
    private String resourceFileContentType;

//Some getter and setters


    }


谢谢。

最佳答案

您可以通过提供装饰器来customize your mappings。为此,您可以创建自己的类,该类实现您的映射器的接口并覆盖所需的映射方法:

public abstract class MediaResourceMapperDecorator implements MediaResourceMapper {

    private final MediaResourceMapper delegate;

    public MediaResourceMapperDecorator(MediaResourceMapper delegate) {
        this.delegate = delegate;
    }

    @Override
    MediaResourceDTO mediaResourceToMediaResourceDTO(MediaResource mediaResource) {
        // Let MapStruct do the basic mapping:
        final MediaResourceDTO dto = this.delegate.mediaResourceToMediaResourceDTO( mediaResource );

        // Then load and add the file to the DTO:
        dto.setResourceFile( loadMyFile( mediaResource.getOriginalMediaFileName() );

        return dto;
    }
}


然后,您在映射器上使用@DecoratedWith批注来引用您的装饰器:

@Mapper(componentModel = "spring", uses = {VehicleMapper.class, })
@DecoratedWith(MediaResourceMapperDecorator.class)
public interface MediaResourceMapper {
    ...

08-06 15:28