简体   繁体   English

如何使用 Mapstruct 和 Kotlin 在另一个映射器中使用映射器?

[英]How to use a mapper in another mapper using Mapstruct and Kotlin?

I would like to map an entity to a DTO with a nested DTO using Mapstruct , in Kotlin .我想在Kotlin中使用Mapstruct将实体 map 到具有嵌套 DTO 的 DTO

I have a first DTO defined as follow:我有一个定义如下的第一个 DTO:

data class FirstDto (
    val something: String
)

This DTO is mapped in an entity and vice-versa using Mapstruct.此 DTO 使用 Mapstruct 映射到实体中,反之亦然。 Here is the Mapper:这是映射器:

@Mapper(componentModel = "spring")
interface FirstMapper {

    fun entityToDto(entity: FirstEntity): FirstDto

    fun dtoToEntity(dto: FirstDto): FirstEntity
}

And a second DTO nesting the first DTO:第二个 DTO 嵌套第一个 DTO:

data class SecondDto (
    val somethingElse: String,
    val firstDto: FirstDto
)

As for the first DTO, I define a Mapper using Mapstruct.至于第一个 DTO,我使用 Mapstruct 定义了一个 Mapper。 But, I would like this mapper to use FirstMapper to map the nested DTO.但是,我希望这个映射器使用FirstMapper到 map 嵌套 DTO。 So I should be using the uses property of the Mapper .所以我应该使用Mapperuses属性。

In Java , this would look like this: @Mapper(componentModel = "spring", uses = FirstMapper.class) .在 Java中,这看起来像这样: @Mapper(componentModel = "spring", uses = FirstMapper.class)

How should it be implemented using Kotlin ?应该如何使用Kotlin来实现?

It doesn't differ much.差别不大。 Purely syntax differences.纯粹的语法差异。

@Mapper(componentModel = "spring", uses = [FirstMapper::class])
interface SecondMapper {
   @Mapping(source = "firstEntity", target = "firstDto")
   fun entityToDto(entity: SecondEntity): SecondDto

   @Mapping(source = "firstDto", target = "firstEntity")
   fun dtoToEntity(dto: SecondDto): SecondEntity
}

Which generates产生

public class SecondMapperImpl implements SecondMapper {
    private final FirstMapper firstMapper = Mappers.getMapper(FirstMapper.class);

    @Override
    public SecondDto entityToDto(SecondEntity entity) {
        ...

        firstDto = firstMapper.entityToDto(entity.getFirstEntity());
        somethingElse = entity.getSomethingElse();
        SecondDto secondDto = new SecondDto(somethingElse, firstDto);
        return secondDto;
    }

    @Override
    public SecondEntity dtoToEntity(SecondDto dto) {
        ...

        firstEntity = firstMapper.dtoToEntity(dto.getFirstDto());
        somethingElse = dto.getSomethingElse();
        SecondEntity secondEntity = new SecondEntity(somethingElse, firstEntity);
        return secondEntity;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM