Reputation: 1063
Say I have incoming object with fields like:
class IncomingRequest {
// ... some fields ommited
String amount; // e.g. "1000.00"
String currency; // e.g. "840"
}
There are more fields which converts great to my DTO:
class MyDto {
// ... some fields which converts great ommited
Amount amount;
}
class Amount {
Long value;
Integer exponent;
Integer currency;
}
, but I want to map this two in custom way like:
@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);
}
meaning I need to write a method to convert only a couple of IncomingRequest
's fields to nested DTO object. How would I achieve that?
UPD: I wouldn't mind if only converted parameters will be passed to method:
default Amount createAmount(String amount, String currency) {
...
}
That would even be better.
Upvotes: 1
Views: 431
Reputation: 4140
Well, there is a construct that maps method parameter like this:
@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);
}
Alternatively you could do aftermappings..
@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) );
}
Note: you could omit @Mappings
in java8
Upvotes: 5