说我有一个带有如下字段的传入对象:
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) {
...
}
那会更好。
答案 0 :(得分:2)
嗯,有一个映射方法参数的结构,如下所示:
@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