考虑以下 POJO:
public class PersonVo {
private String firstName;
private String lastName;
}
private class PersonEntity {
private String fullName;
}
Run Code Online (Sandbox Code Playgroud)
使用 MapStruct,我想创建映射PersonVo到PersonEntity.
我需要映射多个源字段firstName,lastName一个目标归档fullName。
这是我想要的伪代码。
[想要解决方案A]
@Mapper
public interface PersonMapper {
@Mapping(target = "fullName", source = {"firstName", "lastName"}, qualifiedByName="toFullName")
PersonEntity toEntity(PersonVo person);
@Named("toFullName")
String translateToFullName(String firstName, String lastName) {
return firstName + lastName;
}
}
Run Code Online (Sandbox Code Playgroud)
[想要解决方案B]
@Mapper
public interface PersonMapper {
@Mapping(target = "fullName", source = PersonVo.class, qualifiedByName="toFullName")
PersonEntity toEntity(PersonVo person);
@Named("toFullName")
String translateToFullName(PersonVo pserson) {
return pserson.getFirstName() + pserson.getLastName();
}
}
Run Code Online (Sandbox Code Playgroud)
有什么办法可以实现吗?
这是我的答案。
@Mapper
public interface PersonMapper {
@Mapping(target = "fullName", source = ".", qualifiedByName="toFullName")
PersonEntity toEntity(PersonVo person);
@Named("toFullName")
String translateToFullName(PersonVo pserson) {
return pserson.getFirstName() + pserson.getLastName();
}
}
Run Code Online (Sandbox Code Playgroud)
重点是
@Mapping(target = "fullName", source = "." ,qualifiedByName="toFullName")
它可以通过参数使用源对象。
| 归档时间: |
|
| 查看次数: |
1024 次 |
| 最近记录: |