我需要将firstName和lastName从source添加到target中的fullName。我想要第一个&姓氏用空格分隔。但我无法为它编写正确的映射。
我的源和目标类-
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;
}
这是我的映射器接口-
@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);
}
在中间添加空间会给我错误-
@Mapping(expression = "java(source.getFirstName()+" "+source.getLastName())", target = "fullName")
是否有其他解决方案或方法?
您需要转义引号"
。
例如
@Mapping(expression = "java(source.getFirstName()+ " " +source.getLastName())", target = "fullName")
我发现了另一种通过使用decorator模式编写Mapping的方法,正如Map Struct文档中提到的那样。
我只是复制粘贴链接和例子在这里。
https://mapstruct.org/documentation/dev/reference/html/#customizing-使用装饰器的映射器
下面是取自mapstruct文档的代码-
@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;
}
}