[英]Mapstruct convert field to object field
我想用 mapStruct 映射兩個對象
public class EntityA
{
@Id
private String id;
@Column
private String anotherField
第二個對象帶有一個對象一個參數
public class ABC
{
private final ObjectXYZ identification;
// another fields
public class ObjectXYZ
{
private final String identification;
我的映射器:
@Mapper
public interface ObjectMapper
{
@Mapping(target = "identification", source = "identification", qualifiedByName = "ObjectXYZ")
ABC toABC(EntityA entity);
EntityA toEntityA(Material material);
@Named("ObjectXYZ")
@Mapping(target = "identification", source = "identification")
ObjectXYZ toObjectXYZ(String identification);
}
我如何將EntityA.id
映射到ABC.identification.identification
對象定義:
public class EntityA {
private String id;
private String anotherField;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getAnotherField() {
return anotherField;
}
}
public class ABC {
private final ObjectXYZ identification;
private final String anotherField;
public ABC(ObjectXYZ identification, String anotherField) {
this.identification = identification;
this.anotherField = anotherField;
}
public String getAnotherField() {
return anotherField;
}
public ObjectXYZ getIdentification() {
return identification;
}
}
public class ObjectXYZ
{
private String identification;
public ObjectXYZ(String identification) {
this.identification = identification;
}
public String getIdentification() {
return identification;
}
}
映射器:
Mapstruct 自動確定映射的方法或構造函數,您只需指定正確的目標\源屬性。
@Mapper
public interface ObjectMapper
{
@Mapping(target = "identification", source = "entity.id")
@Mapping(target = "anotherField", source = "entity.anotherField")
ABC toABC(EntityA entity);
@Mapping(target = "identification", source = "identification")
ObjectXYZ toObjectXYZ(String identification);
}
生成的代碼:
public class ObjectMapperImpl implements ObjectMapper {
@Override
public ABC toABC(EntityA entity) {
if ( entity == null ) {
return null;
}
ObjectXYZ identification = null;
String anotherField = null;
identification = toObjectXYZ( entity.getId() );
anotherField = entity.getAnotherField();
ABC aBC = new ABC( identification, anotherField );
return aBC;
}
@Override
public ObjectXYZ toObjectXYZ(String identification) {
if ( identification == null ) {
return null;
}
String identification1 = null;
identification1 = identification;
ObjectXYZ objectXYZ = new ObjectXYZ( identification1 );
return objectXYZ;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.