使用自定义方法将字段映射到嵌套对象

问题描述 投票:0回答:1

说我有带有如下字段的传入对象:

class IncomingRequest {
    // ... some fields ommited
    String amount;   // e.g. "1000.00"
    String currency; // e.g. "840"
}

还有更多字段可以很好地转换为我的DTO:

class MyDto {
    // ... some fields which converts great ommited
    Amount amount;
}

class Amount {
    Long value;
    Integer exponent;
    Integer currency;
}

,但我想以自定义方式映射这两个:

@Mapper
public interface DtoMapper {

    @Mappings({ ... some mappings that works great ommited })
    MyDto convert(IncomingRequest request);

    @Mapping( /* what should I use here ? */ )
    default Amount createAmount(IncomingRequest request) {
        long value = ....
        int exponent = ....
        int currency = ....
        return new Amount(value, exponent, currency);
}

意味着我需要编写一种方法,仅将IncomingRequest的几个字段转换为嵌套的DTO对象。我将如何实现?

UPD:我不介意是否仅将转换后的参数传递给方法:

default Amount createAmount(String amount, String currency) {
    ...
}

那会更好。

java mapstruct
1个回答
0
投票

嗯,有一个映射这样的方法参数的构造:

@Mapper
public interface DtoMapper {

    @Mapping( target = "amount", source = "request" /* the param name */ )
    MyDto convert(IncomingRequest request);

    // @Mapping( /* what should I use here ? Answer: nothing its an implemented method.. @Mapping does not make sense */ )
    default Amount createAmount(IncomingRequest request) {
        long value = ....
        int exponent = ....
        int currency = ....
        return new Amount(value, exponent, currency);
}

或者,您可以进行后映射。。

@Mapper
public interface DtoMapper {

    @Mapping( target = amount, ignore = true /* leave it to after mapping */ )
    MyDto convert(IncomingRequest request);

    @AfterMapping(  )
    default void createAmount(IncomingRequest request, @MappingTarget MyDto dto) {
        // which completes the stuff you cannot do
        dto.setAmount( new Amount(value, exponent, currency) );
}

注意:您可以在Java8中省略@Mappings

© www.soinside.com 2019 - 2024. All rights reserved.