简体   繁体   中英

How to add space in expression in MapStruct

I have a requirement to add firstName and lastName from source to fullName in target. I want first & last name to be separated by space. But I am unable to write the proper mapping for it.

My Source and target class-

public class Source {
    private int id;
    private String firstName;
    private String lastName;
    private List<String> addressList;
}

public class Target {
    private int id;
    private String fullName;
    private String city;
}

Here is my mapper interface-

@Mapper
public interface SourceTargetMapper {

    SourceTargetMapper INSTANCE = Mappers.getMapper(SourceTargetMapper.class);

    @Mapping(expression = "java(source.getFirstName()+source.getLastName())", target = "fullName")
    @Mapping(expression = "java(source.getAddressList().get(0))", target = "city")
    Target sourceToTarget(Source source);

    @InheritInverseConfiguration
    Source targetToSource(Target target);
}

Adding space in middle is giving me error-

@Mapping(expression = "java(source.getFirstName()+" "+source.getLastName())", target = "fullName")

If there is any other solution or any approach for this?

You will need to escape the quote " .

eg

@Mapping(expression = "java(source.getFirstName()+ \" \" +source.getLastName())", target = "fullName")

I found another way to write the Mapping by using decorator pattern as mentioned in the Map Struct documentation by using the decorator pattern.

I will just copy paste the link and example here.

https://mapstruct.org/documentation/dev/reference/html/#customizing-mappers-using-decorators

And here goes the code taken from mapstruct documentation -

@Mapper
@DecoratedWith(PersonMapperDecorator.class)
public interface PersonMapper {

    PersonMapper INSTANCE = Mappers.getMapper( PersonMapper.class );

    PersonDto personToPersonDto(Person person);

    AddressDto addressToAddressDto(Address address);
}


public abstract class PersonMapperDecorator implements PersonMapper {

    private final PersonMapper delegate;

    public PersonMapperDecorator(PersonMapper delegate) {
        this.delegate = delegate;
    }

    @Override
    public PersonDto personToPersonDto(Person person) {
        PersonDto dto = delegate.personToPersonDto( person );
        dto.setFullName( person.getFirstName() + " " + person.getLastName() );
        return dto;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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